1 #![allow(unsafe_op_in_unsafe_fn)]
3 use crate::ffi::c_void;
5 use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst};
6 use crate::sys::hermit::abi;
7 use crate::sys::mutex::Mutex;
8 use crate::time::Duration;
10 // The implementation is inspired by Andrew D. Birrell's paper
11 // "Implementing Condition Variables with Semaphores"
19 unsafe impl Send for Condvar {}
20 unsafe impl Sync for Condvar {}
23 pub const fn new() -> Condvar {
24 Condvar { counter: AtomicUsize::new(0), sem1: ptr::null(), sem2: ptr::null() }
27 pub unsafe fn init(&mut self) {
28 let _ = abi::sem_init(&mut self.sem1 as *mut *const c_void, 0);
29 let _ = abi::sem_init(&mut self.sem2 as *mut *const c_void, 0);
32 pub unsafe fn notify_one(&self) {
33 if self.counter.load(SeqCst) > 0 {
34 self.counter.fetch_sub(1, SeqCst);
35 abi::sem_post(self.sem1);
36 abi::sem_timedwait(self.sem2, 0);
40 pub unsafe fn notify_all(&self) {
41 let counter = self.counter.swap(0, SeqCst);
43 abi::sem_post(self.sem1);
46 abi::sem_timedwait(self.sem2, 0);
50 pub unsafe fn wait(&self, mutex: &Mutex) {
51 self.counter.fetch_add(1, SeqCst);
53 abi::sem_timedwait(self.sem1, 0);
54 abi::sem_post(self.sem2);
58 pub unsafe fn wait_timeout(&self, _mutex: &Mutex, _dur: Duration) -> bool {
59 panic!("wait_timeout not supported on hermit");
62 pub unsafe fn destroy(&self) {
63 let _ = abi::sem_destroy(self.sem1);
64 let _ = abi::sem_destroy(self.sem2);