1 use crate::cell::UnsafeCell;
2 use crate::sys::mutex::{self, Mutex};
3 use crate::time::Duration;
5 pub struct Condvar { inner: UnsafeCell<libc::pthread_cond_t> }
7 unsafe impl Send for Condvar {}
8 unsafe impl Sync for Condvar {}
10 const TIMESPEC_MAX: libc::timespec = libc::timespec {
11 tv_sec: <libc::time_t>::max_value(),
12 tv_nsec: 1_000_000_000 - 1,
15 fn saturating_cast_to_time_t(value: u64) -> libc::time_t {
16 if value > <libc::time_t>::max_value() as u64 {
17 <libc::time_t>::max_value()
24 pub const fn new() -> Condvar {
25 // Might be moved and address is changing it is better to avoid
26 // initialization of potentially opaque OS data before it landed
27 Condvar { inner: UnsafeCell::new(libc::PTHREAD_COND_INITIALIZER) }
30 pub unsafe fn init(&mut self) {
31 use crate::mem::MaybeUninit;
32 let mut attr = MaybeUninit::<libc::pthread_condattr_t>::uninit();
33 let r = libc::pthread_condattr_init(attr.as_mut_ptr());
35 let r = libc::pthread_condattr_setclock(attr.as_mut_ptr(), libc::CLOCK_MONOTONIC);
37 let r = libc::pthread_cond_init(self.inner.get(), attr.as_ptr());
39 let r = libc::pthread_condattr_destroy(attr.as_mut_ptr());
44 pub unsafe fn notify_one(&self) {
45 let r = libc::pthread_cond_signal(self.inner.get());
46 debug_assert_eq!(r, 0);
50 pub unsafe fn notify_all(&self) {
51 let r = libc::pthread_cond_broadcast(self.inner.get());
52 debug_assert_eq!(r, 0);
56 pub unsafe fn wait(&self, mutex: &Mutex) {
57 let r = libc::pthread_cond_wait(self.inner.get(), mutex::raw(mutex));
58 debug_assert_eq!(r, 0);
61 // This implementation is used on systems that support pthread_condattr_setclock
62 // where we configure condition variable to use monotonic clock (instead of
63 // default system clock). This approach avoids all problems that result
64 // from changes made to the system time.
65 pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
68 let mut now: libc::timespec = mem::zeroed();
69 let r = libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut now);
72 // Nanosecond calculations can't overflow because both values are below 1e9.
73 let nsec = dur.subsec_nanos() + now.tv_nsec as u32;
75 let sec = saturating_cast_to_time_t(dur.as_secs())
76 .checked_add((nsec / 1_000_000_000) as libc::time_t)
77 .and_then(|s| s.checked_add(now.tv_sec));
78 let nsec = nsec % 1_000_000_000;
80 let timeout = sec.map(|s| {
81 libc::timespec { tv_sec: s, tv_nsec: nsec as _}
82 }).unwrap_or(TIMESPEC_MAX);
84 let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex),
86 assert!(r == libc::ETIMEDOUT || r == 0);
92 pub unsafe fn destroy(&self) {
93 let r = libc::pthread_cond_destroy(self.inner.get());
94 debug_assert_eq!(r, 0);