-
-
Notifications
You must be signed in to change notification settings - Fork 605
/
Copy pathnotify_mutex.rs
48 lines (43 loc) · 891 Bytes
/
notify_mutex.rs
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
use std::sync::{Arc, Condvar, Mutex};
/// combines a `Mutex` and `Condvar` to allow waiting for a change in the variable protected by the `Mutex`
#[derive(Clone, Debug)]
pub struct NotifyableMutex<T>
where
T: Send + Sync,
{
data: Arc<(Mutex<T>, Condvar)>,
}
impl<T> NotifyableMutex<T>
where
T: Send + Sync,
{
///
pub fn new(start_value: T) -> Self {
Self {
data: Arc::new((Mutex::new(start_value), Condvar::new())),
}
}
///
pub fn wait(&self, condition: T)
where
T: PartialEq + Copy,
{
let mut data = self.data.0.lock().expect("lock err");
while *data != condition {
data = self.data.1.wait(data).expect("wait err");
}
drop(data);
}
///
pub fn set_and_notify(&self, value: T) {
*self.data.0.lock().expect("set err") = value;
self.data.1.notify_one();
}
///
pub fn get(&self) -> T
where
T: Copy,
{
*self.data.0.lock().expect("get err")
}
}