1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//! Condition variable for thread coordination.
//!
//! This module provides async condition variable functionality for coordinating
//! tasks that need to wait for certain conditions to become true.
use crate::diagnostics::Result;
use super::ConcurrencyError;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Notify;
/// Condition variable for thread coordination.
#[derive(Debug, Clone)]
pub struct CondVar {
notify: Arc<Notify>,
name: Option<String>,
}
impl CondVar {
/// Creates a new condition variable.
pub fn new() -> Self {
Self {
notify: Arc::new(Notify::new()),
name: None,
}
}
/// Creates a new named condition variable.
pub fn with_name(name: String) -> Self {
Self {
notify: Arc::new(Notify::new()),
name: Some(name),
}
}
/// Waits for a notification.
pub async fn wait(&self) {
self.notify.notified().await;
}
/// Waits for a notification with a timeout.
pub async fn wait_timeout(&self, duration: Duration) -> Result<()> {
match tokio::time::timeout(duration, self.wait()).await {
Ok(_) => Ok(()),
Err(_) => Err(ConcurrencyError::Timeout.into()),
}
}
/// Notifies one waiting task.
pub fn notify_one(&self) {
self.notify.notify_one();
}
/// Notifies all waiting tasks.
pub fn notify_all(&self) {
self.notify.notify_waiters();
}
/// Gets the name of the condition variable.
pub fn name(&self) -> Option<&str> {
self.name.as_deref()
}
}
impl Default for CondVar {
fn default() -> Self {
Self::new()
}
}