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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use std::{
sync::{Condvar, Mutex},
time::Duration,
};
#[derive(Default, Debug)]
pub struct WaitableCondvar {
pub mutex: Mutex<()>,
pub event: Condvar,
}
impl WaitableCondvar {
pub fn notify_all(&self) {
self.event.notify_all();
}
pub fn notify_one(&self) {
self.event.notify_one();
}
pub fn wait_timeout(&self, timeout: Duration) -> bool {
let lock = self.mutex.lock().unwrap();
let res = self.event.wait_timeout(lock, timeout).unwrap();
if res.1.timed_out() {
return true;
}
false
}
}
#[cfg(test)]
pub mod tests {
use {
super::*,
std::{
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
thread::Builder,
},
};
#[ignore]
#[test]
fn test_waitable_condvar() {
let data = Arc::new(AtomicBool::new(false));
let data_ = data.clone();
let cv = Arc::new(WaitableCondvar::default());
let cv2 = Arc::new(WaitableCondvar::default());
let cv_ = cv.clone();
let cv2_ = cv2.clone();
let cv2__ = cv2.clone();
let passes = 3;
let handle = Builder::new().spawn(move || {
for _pass in 0..passes {
let mut notified = false;
while cv2_.wait_timeout(Duration::from_millis(1)) {
if !notified && data_.load(Ordering::Relaxed) {
notified = true;
cv_.notify_all();
}
}
assert!(data_.swap(false, Ordering::Relaxed));
}
});
let handle2 = Builder::new().spawn(move || {
for _pass in 0..(passes - 1) {
assert!(!cv2__.wait_timeout(Duration::from_millis(10000))); }
});
for _pass in 0..passes {
assert!(cv.wait_timeout(Duration::from_millis(1)));
assert!(!data.swap(true, Ordering::Relaxed));
assert!(!cv.wait_timeout(Duration::from_millis(10000))); cv2.notify_all();
}
assert!(handle.unwrap().join().is_ok());
assert!(handle2.unwrap().join().is_ok());
}
}