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 #[cfg(any(target_os = "macos",
33 target_os = "android",
35 target_os = "redox"))]
36 pub unsafe fn init(&mut self) {}
38 #[cfg(not(any(target_os = "macos",
41 target_os = "android",
43 target_os = "redox")))]
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",
81 target_os = "android",
82 target_os = "hermit")))]
83 pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
86 let mut now: libc::timespec = mem::zeroed();
87 let r = libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut now);
90 // Nanosecond calculations can't overflow because both values are below 1e9.
91 let nsec = dur.subsec_nanos() + now.tv_nsec as u32;
93 let sec = saturating_cast_to_time_t(dur.as_secs())
94 .checked_add((nsec / 1_000_000_000) as libc::time_t)
95 .and_then(|s| s.checked_add(now.tv_sec));
96 let nsec = nsec % 1_000_000_000;
98 let timeout = sec.map(|s| {
99 libc::timespec { tv_sec: s, tv_nsec: nsec as _}
100 }).unwrap_or(TIMESPEC_MAX);
102 let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex),
104 assert!(r == libc::ETIMEDOUT || r == 0);
109 // This implementation is modeled after libcxx's condition_variable
110 // https://github.com/llvm-mirror/libcxx/blob/release_35/src/condition_variable.cpp#L46
111 // https://github.com/llvm-mirror/libcxx/blob/release_35/include/__mutex_base#L367
112 #[cfg(any(target_os = "macos", target_os = "ios", target_os = "android", target_os = "hermit"))]
113 pub unsafe fn wait_timeout(&self, mutex: &Mutex, mut dur: Duration) -> bool {
115 use crate::time::Instant;
118 let max_dur = Duration::from_secs(1000 * 365 * 86400);
121 // OSX implementation of `pthread_cond_timedwait` is buggy
122 // with super long durations. When duration is greater than
123 // 0x100_0000_0000_0000 seconds, `pthread_cond_timedwait`
124 // in macOS Sierra return error 316.
126 // This program demonstrates the issue:
127 // https://gist.github.com/stepancheg/198db4623a20aad2ad7cddb8fda4a63c
129 // To work around this issue, and possible bugs of other OSes, timeout
130 // is clamped to 1000 years, which is allowable per the API of `wait_timeout`
131 // because of spurious wakeups.
136 // First, figure out what time it currently is, in both system and
137 // stable time. pthread_cond_timedwait uses system time, but we want to
138 // report timeout based on stable time.
139 let mut sys_now = libc::timeval { tv_sec: 0, tv_usec: 0 };
140 let stable_now = Instant::now();
141 let r = libc::gettimeofday(&mut sys_now, ptr::null_mut());
142 debug_assert_eq!(r, 0);
144 let nsec = dur.subsec_nanos() as libc::c_long +
145 (sys_now.tv_usec * 1000) as libc::c_long;
146 let extra = (nsec / 1_000_000_000) as libc::time_t;
147 let nsec = nsec % 1_000_000_000;
148 let seconds = saturating_cast_to_time_t(dur.as_secs());
150 let timeout = sys_now.tv_sec.checked_add(extra).and_then(|s| {
151 s.checked_add(seconds)
153 libc::timespec { tv_sec: s, tv_nsec: nsec }
154 }).unwrap_or(TIMESPEC_MAX);
157 let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex),
159 debug_assert!(r == libc::ETIMEDOUT || r == 0);
161 // ETIMEDOUT is not a totally reliable method of determining timeout due
162 // to clock shifts, so do the check ourselves
163 stable_now.elapsed() < dur
167 #[cfg(not(target_os = "dragonfly"))]
168 pub unsafe fn destroy(&self) {
169 let r = libc::pthread_cond_destroy(self.inner.get());
170 debug_assert_eq!(r, 0);
174 #[cfg(target_os = "dragonfly")]
175 pub unsafe fn destroy(&self) {
176 let r = libc::pthread_cond_destroy(self.inner.get());
177 // On DragonFly pthread_cond_destroy() returns EINVAL if called on
178 // a condvar that was just initialized with
179 // libc::PTHREAD_COND_INITIALIZER. Once it is used or
180 // pthread_cond_init() is called, this behaviour no longer occurs.
181 debug_assert!(r == 0 || r == libc::EINVAL);