1 use crate::cell::UnsafeCell;
2 use crate::sys::mutex::{self, Mutex};
3 use crate::time::Duration;
6 inner: UnsafeCell<libc::pthread_cond_t>,
9 unsafe impl Send for Condvar {}
10 unsafe impl Sync for Condvar {}
12 const TIMESPEC_MAX: libc::timespec =
13 libc::timespec { tv_sec: <libc::time_t>::MAX, 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 as u64 { <libc::time_t>::MAX } else { value as libc::time_t }
20 pub const fn new() -> Condvar {
21 // Might be moved and address is changing it is better to avoid
22 // initialization of potentially opaque OS data before it landed
23 Condvar { inner: UnsafeCell::new(libc::PTHREAD_COND_INITIALIZER) }
30 target_os = "android",
33 pub unsafe fn init(&mut self) {}
39 target_os = "android",
42 pub unsafe fn init(&mut self) {
43 use crate::mem::MaybeUninit;
44 let mut attr = MaybeUninit::<libc::pthread_condattr_t>::uninit();
45 let r = libc::pthread_condattr_init(attr.as_mut_ptr());
47 let r = libc::pthread_condattr_setclock(attr.as_mut_ptr(), libc::CLOCK_MONOTONIC);
49 let r = libc::pthread_cond_init(self.inner.get(), attr.as_ptr());
51 let r = libc::pthread_condattr_destroy(attr.as_mut_ptr());
56 pub unsafe fn notify_one(&self) {
57 let r = libc::pthread_cond_signal(self.inner.get());
58 debug_assert_eq!(r, 0);
62 pub unsafe fn notify_all(&self) {
63 let r = libc::pthread_cond_broadcast(self.inner.get());
64 debug_assert_eq!(r, 0);
68 pub unsafe fn wait(&self, mutex: &Mutex) {
69 let r = libc::pthread_cond_wait(self.inner.get(), mutex::raw(mutex));
70 debug_assert_eq!(r, 0);
73 // This implementation is used on systems that support pthread_condattr_setclock
74 // where we configure condition variable to use monotonic clock (instead of
75 // default system clock). This approach avoids all problems that result
76 // from changes made to the system time.
77 #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "android")))]
78 pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
81 let mut now: libc::timespec = mem::zeroed();
82 let r = libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut now);
85 // Nanosecond calculations can't overflow because both values are below 1e9.
86 let nsec = dur.subsec_nanos() + now.tv_nsec as u32;
88 let sec = saturating_cast_to_time_t(dur.as_secs())
89 .checked_add((nsec / 1_000_000_000) as libc::time_t)
90 .and_then(|s| s.checked_add(now.tv_sec));
91 let nsec = nsec % 1_000_000_000;
94 sec.map(|s| libc::timespec { tv_sec: s, tv_nsec: nsec as _ }).unwrap_or(TIMESPEC_MAX);
96 let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex), &timeout);
97 assert!(r == libc::ETIMEDOUT || r == 0);
101 // This implementation is modeled after libcxx's condition_variable
102 // https://github.com/llvm-mirror/libcxx/blob/release_35/src/condition_variable.cpp#L46
103 // https://github.com/llvm-mirror/libcxx/blob/release_35/include/__mutex_base#L367
104 #[cfg(any(target_os = "macos", target_os = "ios", target_os = "android"))]
105 pub unsafe fn wait_timeout(&self, mutex: &Mutex, mut dur: Duration) -> bool {
107 use crate::time::Instant;
110 let max_dur = Duration::from_secs(1000 * 365 * 86400);
113 // OSX implementation of `pthread_cond_timedwait` is buggy
114 // with super long durations. When duration is greater than
115 // 0x100_0000_0000_0000 seconds, `pthread_cond_timedwait`
116 // in macOS Sierra return error 316.
118 // This program demonstrates the issue:
119 // https://gist.github.com/stepancheg/198db4623a20aad2ad7cddb8fda4a63c
121 // To work around this issue, and possible bugs of other OSes, timeout
122 // is clamped to 1000 years, which is allowable per the API of `wait_timeout`
123 // because of spurious wakeups.
128 // First, figure out what time it currently is, in both system and
129 // stable time. pthread_cond_timedwait uses system time, but we want to
130 // report timeout based on stable time.
131 let mut sys_now = libc::timeval { tv_sec: 0, tv_usec: 0 };
132 let stable_now = Instant::now();
133 let r = libc::gettimeofday(&mut sys_now, ptr::null_mut());
134 debug_assert_eq!(r, 0);
136 let nsec = dur.subsec_nanos() as libc::c_long + (sys_now.tv_usec * 1000) as libc::c_long;
137 let extra = (nsec / 1_000_000_000) as libc::time_t;
138 let nsec = nsec % 1_000_000_000;
139 let seconds = saturating_cast_to_time_t(dur.as_secs());
141 let timeout = sys_now
144 .and_then(|s| s.checked_add(seconds))
145 .map(|s| libc::timespec { tv_sec: s, tv_nsec: nsec })
146 .unwrap_or(TIMESPEC_MAX);
149 let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex), &timeout);
150 debug_assert!(r == libc::ETIMEDOUT || r == 0);
152 // ETIMEDOUT is not a totally reliable method of determining timeout due
153 // to clock shifts, so do the check ourselves
154 stable_now.elapsed() < dur
158 #[cfg(not(target_os = "dragonfly"))]
159 pub unsafe fn destroy(&self) {
160 let r = libc::pthread_cond_destroy(self.inner.get());
161 debug_assert_eq!(r, 0);
165 #[cfg(target_os = "dragonfly")]
166 pub unsafe fn destroy(&self) {
167 let r = libc::pthread_cond_destroy(self.inner.get());
168 // On DragonFly pthread_cond_destroy() returns EINVAL if called on
169 // a condvar that was just initialized with
170 // libc::PTHREAD_COND_INITIALIZER. Once it is used or
171 // pthread_cond_init() is called, this behaviour no longer occurs.
172 debug_assert!(r == 0 || r == libc::EINVAL);