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 pub type MovableCondvar = Box<Condvar>;
11 unsafe impl Send for Condvar {}
12 unsafe impl Sync for Condvar {}
14 const TIMESPEC_MAX: libc::timespec =
15 libc::timespec { tv_sec: <libc::time_t>::MAX, tv_nsec: 1_000_000_000 - 1 };
17 fn saturating_cast_to_time_t(value: u64) -> libc::time_t {
18 if value > <libc::time_t>::MAX as u64 { <libc::time_t>::MAX } else { value as libc::time_t }
22 pub const fn new() -> Condvar {
23 // Might be moved and address is changing it is better to avoid
24 // initialization of potentially opaque OS data before it landed
25 Condvar { inner: UnsafeCell::new(libc::PTHREAD_COND_INITIALIZER) }
32 target_os = "android",
35 pub unsafe fn init(&mut self) {}
41 target_os = "android",
44 pub unsafe fn init(&mut self) {
45 use crate::mem::MaybeUninit;
46 let mut attr = MaybeUninit::<libc::pthread_condattr_t>::uninit();
47 let r = libc::pthread_condattr_init(attr.as_mut_ptr());
49 let r = libc::pthread_condattr_setclock(attr.as_mut_ptr(), libc::CLOCK_MONOTONIC);
51 let r = libc::pthread_cond_init(self.inner.get(), attr.as_ptr());
53 let r = libc::pthread_condattr_destroy(attr.as_mut_ptr());
58 pub unsafe fn notify_one(&self) {
59 let r = libc::pthread_cond_signal(self.inner.get());
60 debug_assert_eq!(r, 0);
64 pub unsafe fn notify_all(&self) {
65 let r = libc::pthread_cond_broadcast(self.inner.get());
66 debug_assert_eq!(r, 0);
70 pub unsafe fn wait(&self, mutex: &Mutex) {
71 let r = libc::pthread_cond_wait(self.inner.get(), mutex::raw(mutex));
72 debug_assert_eq!(r, 0);
75 // This implementation is used on systems that support pthread_condattr_setclock
76 // where we configure condition variable to use monotonic clock (instead of
77 // default system clock). This approach avoids all problems that result
78 // from changes made to the system time.
79 #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "android")))]
80 pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
83 let mut now: libc::timespec = mem::zeroed();
84 let r = libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut now);
87 // Nanosecond calculations can't overflow because both values are below 1e9.
88 let nsec = dur.subsec_nanos() + now.tv_nsec as u32;
90 let sec = saturating_cast_to_time_t(dur.as_secs())
91 .checked_add((nsec / 1_000_000_000) as libc::time_t)
92 .and_then(|s| s.checked_add(now.tv_sec));
93 let nsec = nsec % 1_000_000_000;
96 sec.map(|s| libc::timespec { tv_sec: s, tv_nsec: nsec as _ }).unwrap_or(TIMESPEC_MAX);
98 let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex), &timeout);
99 assert!(r == libc::ETIMEDOUT || r == 0);
103 // This implementation is modeled after libcxx's condition_variable
104 // https://github.com/llvm-mirror/libcxx/blob/release_35/src/condition_variable.cpp#L46
105 // https://github.com/llvm-mirror/libcxx/blob/release_35/include/__mutex_base#L367
106 #[cfg(any(target_os = "macos", target_os = "ios", target_os = "android"))]
107 pub unsafe fn wait_timeout(&self, mutex: &Mutex, mut dur: Duration) -> bool {
109 use crate::time::Instant;
112 let max_dur = Duration::from_secs(1000 * 365 * 86400);
115 // OSX implementation of `pthread_cond_timedwait` is buggy
116 // with super long durations. When duration is greater than
117 // 0x100_0000_0000_0000 seconds, `pthread_cond_timedwait`
118 // in macOS Sierra return error 316.
120 // This program demonstrates the issue:
121 // https://gist.github.com/stepancheg/198db4623a20aad2ad7cddb8fda4a63c
123 // To work around this issue, and possible bugs of other OSes, timeout
124 // is clamped to 1000 years, which is allowable per the API of `wait_timeout`
125 // because of spurious wakeups.
130 // First, figure out what time it currently is, in both system and
131 // stable time. pthread_cond_timedwait uses system time, but we want to
132 // report timeout based on stable time.
133 let mut sys_now = libc::timeval { tv_sec: 0, tv_usec: 0 };
134 let stable_now = Instant::now();
135 let r = libc::gettimeofday(&mut sys_now, ptr::null_mut());
136 debug_assert_eq!(r, 0);
138 let nsec = dur.subsec_nanos() as libc::c_long + (sys_now.tv_usec * 1000) as libc::c_long;
139 let extra = (nsec / 1_000_000_000) as libc::time_t;
140 let nsec = nsec % 1_000_000_000;
141 let seconds = saturating_cast_to_time_t(dur.as_secs());
143 let timeout = sys_now
146 .and_then(|s| s.checked_add(seconds))
147 .map(|s| libc::timespec { tv_sec: s, tv_nsec: nsec })
148 .unwrap_or(TIMESPEC_MAX);
151 let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex), &timeout);
152 debug_assert!(r == libc::ETIMEDOUT || r == 0);
154 // ETIMEDOUT is not a totally reliable method of determining timeout due
155 // to clock shifts, so do the check ourselves
156 stable_now.elapsed() < dur
160 #[cfg(not(target_os = "dragonfly"))]
161 pub unsafe fn destroy(&self) {
162 let r = libc::pthread_cond_destroy(self.inner.get());
163 debug_assert_eq!(r, 0);
167 #[cfg(target_os = "dragonfly")]
168 pub unsafe fn destroy(&self) {
169 let r = libc::pthread_cond_destroy(self.inner.get());
170 // On DragonFly pthread_cond_destroy() returns EINVAL if called on
171 // a condvar that was just initialized with
172 // libc::PTHREAD_COND_INITIALIZER. Once it is used or
173 // pthread_cond_init() is called, this behaviour no longer occurs.
174 debug_assert!(r == 0 || r == libc::EINVAL);