1 use crate::cell::UnsafeCell;
3 use crate::sync::atomic::{AtomicPtr, Ordering::Relaxed};
4 use crate::sys::locks::{pthread_mutex, Mutex};
5 use crate::sys::time::TIMESPEC_MAX;
6 use crate::sys_common::lazy_box::{LazyBox, LazyInit};
7 use crate::time::Duration;
9 struct AllocatedCondvar(UnsafeCell<libc::pthread_cond_t>);
12 inner: LazyBox<AllocatedCondvar>,
13 mutex: AtomicPtr<libc::pthread_mutex_t>,
17 fn raw(c: &Condvar) -> *mut libc::pthread_cond_t {
21 unsafe impl Send for AllocatedCondvar {}
22 unsafe impl Sync for AllocatedCondvar {}
24 impl LazyInit for AllocatedCondvar {
25 fn init() -> Box<Self> {
26 let condvar = Box::new(AllocatedCondvar(UnsafeCell::new(libc::PTHREAD_COND_INITIALIZER)));
32 target_os = "watchos",
34 target_os = "android",
37 // `pthread_condattr_setclock` is unfortunately not supported on these platforms.
38 } else if #[cfg(any(target_os = "espidf", target_os = "horizon"))] {
39 // NOTE: ESP-IDF's PTHREAD_COND_INITIALIZER support is not released yet
40 // So on that platform, init() should always be called
41 // Moreover, that platform does not have pthread_condattr_setclock support,
42 // hence that initialization should be skipped as well
44 // Similar story for the 3DS (horizon).
45 let r = unsafe { libc::pthread_cond_init(condvar.0.get(), crate::ptr::null()) };
48 use crate::mem::MaybeUninit;
49 let mut attr = MaybeUninit::<libc::pthread_condattr_t>::uninit();
50 let r = unsafe { libc::pthread_condattr_init(attr.as_mut_ptr()) };
52 let r = unsafe { libc::pthread_condattr_setclock(attr.as_mut_ptr(), libc::CLOCK_MONOTONIC) };
54 let r = unsafe { libc::pthread_cond_init(condvar.0.get(), attr.as_ptr()) };
56 let r = unsafe { libc::pthread_condattr_destroy(attr.as_mut_ptr()) };
65 impl Drop for AllocatedCondvar {
68 let r = unsafe { libc::pthread_cond_destroy(self.0.get()) };
69 if cfg!(target_os = "dragonfly") {
70 // On DragonFly pthread_cond_destroy() returns EINVAL if called on
71 // a condvar that was just initialized with
72 // libc::PTHREAD_COND_INITIALIZER. Once it is used or
73 // pthread_cond_init() is called, this behaviour no longer occurs.
74 debug_assert!(r == 0 || r == libc::EINVAL);
76 debug_assert_eq!(r, 0);
82 pub const fn new() -> Condvar {
83 Condvar { inner: LazyBox::new(), mutex: AtomicPtr::new(ptr::null_mut()) }
87 fn verify(&self, mutex: *mut libc::pthread_mutex_t) {
88 // Relaxed is okay here because we never read through `self.addr`, and only use it to
90 match self.mutex.compare_exchange(ptr::null_mut(), mutex, Relaxed, Relaxed) {
91 Ok(_) => {} // Stored the address
92 Err(n) if n == mutex => {} // Lost a race to store the same address
93 _ => panic!("attempted to use a condition variable with two mutexes"),
98 pub fn notify_one(&self) {
99 let r = unsafe { libc::pthread_cond_signal(raw(self)) };
100 debug_assert_eq!(r, 0);
104 pub fn notify_all(&self) {
105 let r = unsafe { libc::pthread_cond_broadcast(raw(self)) };
106 debug_assert_eq!(r, 0);
110 pub unsafe fn wait(&self, mutex: &Mutex) {
111 let mutex = pthread_mutex::raw(mutex);
113 let r = libc::pthread_cond_wait(raw(self), mutex);
114 debug_assert_eq!(r, 0);
117 // This implementation is used on systems that support pthread_condattr_setclock
118 // where we configure condition variable to use monotonic clock (instead of
119 // default system clock). This approach avoids all problems that result
120 // from changes made to the system time.
124 target_os = "watchos",
125 target_os = "android",
126 target_os = "espidf",
127 target_os = "horizon"
129 pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
130 use crate::sys::time::Timespec;
132 let mutex = pthread_mutex::raw(mutex);
135 let timeout = Timespec::now(libc::CLOCK_MONOTONIC)
136 .checked_add_duration(&dur)
137 .and_then(|t| t.to_timespec())
138 .unwrap_or(TIMESPEC_MAX);
139 let r = libc::pthread_cond_timedwait(raw(self), mutex, &timeout);
140 assert!(r == libc::ETIMEDOUT || r == 0);
144 // This implementation is modeled after libcxx's condition_variable
145 // https://github.com/llvm-mirror/libcxx/blob/release_35/src/condition_variable.cpp#L46
146 // https://github.com/llvm-mirror/libcxx/blob/release_35/include/__mutex_base#L367
150 target_os = "watchos",
151 target_os = "android",
152 target_os = "espidf",
153 target_os = "horizon"
155 pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
156 use crate::sys::time::SystemTime;
157 use crate::time::Instant;
159 let mutex = pthread_mutex::raw(mutex);
162 // OSX implementation of `pthread_cond_timedwait` is buggy
163 // with super long durations. When duration is greater than
164 // 0x100_0000_0000_0000 seconds, `pthread_cond_timedwait`
165 // in macOS Sierra returns error 316.
167 // This program demonstrates the issue:
168 // https://gist.github.com/stepancheg/198db4623a20aad2ad7cddb8fda4a63c
170 // To work around this issue, and possible bugs of other OSes, timeout
171 // is clamped to 1000 years, which is allowable per the API of `wait_timeout`
172 // because of spurious wakeups.
173 let dur = Duration::min(dur, Duration::from_secs(1000 * 365 * 86400));
175 // pthread_cond_timedwait uses system time, but we want to report timeout
176 // based on stable time.
177 let now = Instant::now();
179 let timeout = SystemTime::now()
181 .checked_add_duration(&dur)
182 .and_then(|t| t.to_timespec())
183 .unwrap_or(TIMESPEC_MAX);
185 let r = libc::pthread_cond_timedwait(raw(self), mutex, &timeout);
186 debug_assert!(r == libc::ETIMEDOUT || r == 0);
188 // ETIMEDOUT is not a totally reliable method of determining timeout due
189 // to clock shifts, so do the check ourselves