forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcondvar.rs
66 lines (55 loc) · 1.78 KB
/
condvar.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use crate::ffi::c_void;
use crate::ptr;
use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst};
use crate::sys::hermit::abi;
use crate::sys::mutex::Mutex;
use crate::time::Duration;
// The implementation is inspired by Andrew D. Birrell's paper
// "Implementing Condition Variables with Semaphores"
pub struct Condvar {
counter: AtomicUsize,
sem1: *const c_void,
sem2: *const c_void,
}
pub type MovableCondvar = Condvar;
unsafe impl Send for Condvar {}
unsafe impl Sync for Condvar {}
impl Condvar {
pub const fn new() -> Condvar {
Condvar { counter: AtomicUsize::new(0), sem1: ptr::null(), sem2: ptr::null() }
}
pub unsafe fn init(&mut self) {
let _ = abi::sem_init(&mut self.sem1 as *mut *const c_void, 0);
let _ = abi::sem_init(&mut self.sem2 as *mut *const c_void, 0);
}
pub unsafe fn notify_one(&self) {
if self.counter.load(SeqCst) > 0 {
self.counter.fetch_sub(1, SeqCst);
abi::sem_post(self.sem1);
abi::sem_timedwait(self.sem2, 0);
}
}
pub unsafe fn notify_all(&self) {
let counter = self.counter.swap(0, SeqCst);
for _ in 0..counter {
abi::sem_post(self.sem1);
}
for _ in 0..counter {
abi::sem_timedwait(self.sem2, 0);
}
}
pub unsafe fn wait(&self, mutex: &Mutex) {
self.counter.fetch_add(1, SeqCst);
mutex.unlock();
abi::sem_timedwait(self.sem1, 0);
abi::sem_post(self.sem2);
mutex.lock();
}
pub unsafe fn wait_timeout(&self, _mutex: &Mutex, _dur: Duration) -> bool {
panic!("wait_timeout not supported on hermit");
}
pub unsafe fn destroy(&self) {
let _ = abi::sem_destroy(self.sem1);
let _ = abi::sem_destroy(self.sem2);
}
}