1 //! Thread parking without `futex` using the `pthread` synchronization primitives.
3 use crate::cell::UnsafeCell;
4 use crate::marker::PhantomPinned;
6 use crate::ptr::addr_of_mut;
7 use crate::sync::atomic::AtomicUsize;
8 use crate::sync::atomic::Ordering::SeqCst;
9 use crate::sys::time::TIMESPEC_MAX;
10 use crate::time::Duration;
12 const EMPTY: usize = 0;
13 const PARKED: usize = 1;
14 const NOTIFIED: usize = 2;
16 unsafe fn lock(lock: *mut libc::pthread_mutex_t) {
17 let r = libc::pthread_mutex_lock(lock);
18 debug_assert_eq!(r, 0);
21 unsafe fn unlock(lock: *mut libc::pthread_mutex_t) {
22 let r = libc::pthread_mutex_unlock(lock);
23 debug_assert_eq!(r, 0);
26 unsafe fn notify_one(cond: *mut libc::pthread_cond_t) {
27 let r = libc::pthread_cond_signal(cond);
28 debug_assert_eq!(r, 0);
31 unsafe fn wait(cond: *mut libc::pthread_cond_t, lock: *mut libc::pthread_mutex_t) {
32 let r = libc::pthread_cond_wait(cond, lock);
33 debug_assert_eq!(r, 0);
36 unsafe fn wait_timeout(
37 cond: *mut libc::pthread_cond_t,
38 lock: *mut libc::pthread_mutex_t,
41 // Use the system clock on systems that do not support pthread_condattr_setclock.
42 // This unfortunately results in problems when the system time changes.
46 target_os = "watchos",
51 use crate::sys::time::SystemTime;
53 // OSX implementation of `pthread_cond_timedwait` is buggy
54 // with super long durations. When duration is greater than
55 // 0x100_0000_0000_0000 seconds, `pthread_cond_timedwait`
56 // in macOS Sierra return error 316.
58 // This program demonstrates the issue:
59 // https://gist.github.com/stepancheg/198db4623a20aad2ad7cddb8fda4a63c
61 // To work around this issue, and possible bugs of other OSes, timeout
62 // is clamped to 1000 years, which is allowable per the API of `park_timeout`
63 // because of spurious wakeups.
64 let dur = min(dur, Duration::from_secs(1000 * 365 * 86400));
65 let now = SystemTime::now().t;
68 // Use the monotonic clock on other systems.
72 target_os = "watchos",
76 use crate::sys::time::Timespec;
78 (Timespec::now(libc::CLOCK_MONOTONIC), dur)
82 now.checked_add_duration(&dur).and_then(|t| t.to_timespec()).unwrap_or(TIMESPEC_MAX);
83 let r = libc::pthread_cond_timedwait(cond, lock, &timeout);
84 debug_assert!(r == libc::ETIMEDOUT || r == 0);
89 lock: UnsafeCell<libc::pthread_mutex_t>,
90 cvar: UnsafeCell<libc::pthread_cond_t>,
91 // The `pthread` primitives require a stable address, so make this struct `!Unpin`.
92 _pinned: PhantomPinned,
96 /// Construct the UNIX parker in-place.
99 /// The constructed parker must never be moved.
100 pub unsafe fn new(parker: *mut Parker) {
101 // Use the default mutex implementation to allow for simpler initialization.
102 // This could lead to undefined behaviour when deadlocking. This is avoided
103 // by not deadlocking. Note in particular the unlocking operation before any
104 // panic, as code after the panic could try to park again.
105 addr_of_mut!((*parker).state).write(AtomicUsize::new(EMPTY));
106 addr_of_mut!((*parker).lock).write(UnsafeCell::new(libc::PTHREAD_MUTEX_INITIALIZER));
112 target_os = "watchos",
114 target_os = "android",
117 addr_of_mut!((*parker).cvar).write(UnsafeCell::new(libc::PTHREAD_COND_INITIALIZER));
118 } else if #[cfg(any(target_os = "espidf", target_os = "horizon"))] {
119 let r = libc::pthread_cond_init(addr_of_mut!((*parker).cvar).cast(), crate::ptr::null());
122 use crate::mem::MaybeUninit;
123 let mut attr = MaybeUninit::<libc::pthread_condattr_t>::uninit();
124 let r = libc::pthread_condattr_init(attr.as_mut_ptr());
126 let r = libc::pthread_condattr_setclock(attr.as_mut_ptr(), libc::CLOCK_MONOTONIC);
128 let r = libc::pthread_cond_init(addr_of_mut!((*parker).cvar).cast(), attr.as_ptr());
130 let r = libc::pthread_condattr_destroy(attr.as_mut_ptr());
136 // This implementation doesn't require `unsafe`, but other implementations
137 // may assume this is only called by the thread that owns the Parker.
138 pub unsafe fn park(self: Pin<&Self>) {
139 // If we were previously notified then we consume this notification and
141 if self.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst).is_ok() {
145 // Otherwise we need to coordinate going to sleep
146 lock(self.lock.get());
147 match self.state.compare_exchange(EMPTY, PARKED, SeqCst, SeqCst) {
150 // We must read here, even though we know it will be `NOTIFIED`.
151 // This is because `unpark` may have been called again since we read
152 // `NOTIFIED` in the `compare_exchange` above. We must perform an
153 // acquire operation that synchronizes with that `unpark` to observe
154 // any writes it made before the call to unpark. To do that we must
155 // read from the write it made to `state`.
156 let old = self.state.swap(EMPTY, SeqCst);
158 unlock(self.lock.get());
160 assert_eq!(old, NOTIFIED, "park state changed unexpectedly");
162 } // should consume this notification, so prohibit spurious wakeups in next park.
164 unlock(self.lock.get());
166 panic!("inconsistent park state")
171 wait(self.cvar.get(), self.lock.get());
173 match self.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst) {
174 Ok(_) => break, // got a notification
175 Err(_) => {} // spurious wakeup, go back to sleep
179 unlock(self.lock.get());
182 // This implementation doesn't require `unsafe`, but other implementations
183 // may assume this is only called by the thread that owns the Parker. Use
184 // `Pin` to guarantee a stable address for the mutex and condition variable.
185 pub unsafe fn park_timeout(self: Pin<&Self>, dur: Duration) {
186 // Like `park` above we have a fast path for an already-notified thread, and
187 // afterwards we start coordinating for a sleep.
189 if self.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst).is_ok() {
193 lock(self.lock.get());
194 match self.state.compare_exchange(EMPTY, PARKED, SeqCst, SeqCst) {
197 // We must read again here, see `park`.
198 let old = self.state.swap(EMPTY, SeqCst);
199 unlock(self.lock.get());
201 assert_eq!(old, NOTIFIED, "park state changed unexpectedly");
203 } // should consume this notification, so prohibit spurious wakeups in next park.
205 unlock(self.lock.get());
206 panic!("inconsistent park_timeout state")
210 // Wait with a timeout, and if we spuriously wake up or otherwise wake up
211 // from a notification we just want to unconditionally set the state back to
212 // empty, either consuming a notification or un-flagging ourselves as
214 wait_timeout(self.cvar.get(), self.lock.get(), dur);
216 match self.state.swap(EMPTY, SeqCst) {
217 NOTIFIED => unlock(self.lock.get()), // got a notification, hurray!
218 PARKED => unlock(self.lock.get()), // no notification, alas
220 unlock(self.lock.get());
221 panic!("inconsistent park_timeout state: {n}")
226 pub fn unpark(self: Pin<&Self>) {
227 // To ensure the unparked thread will observe any writes we made
228 // before this call, we must perform a release operation that `park`
229 // can synchronize with. To do that we must write `NOTIFIED` even if
230 // `state` is already `NOTIFIED`. That is why this must be a swap
231 // rather than a compare-and-swap that returns if it reads `NOTIFIED`
233 match self.state.swap(NOTIFIED, SeqCst) {
234 EMPTY => return, // no one was waiting
235 NOTIFIED => return, // already unparked
236 PARKED => {} // gotta go wake someone up
237 _ => panic!("inconsistent state in unpark"),
240 // There is a period between when the parked thread sets `state` to
241 // `PARKED` (or last checked `state` in the case of a spurious wake
242 // up) and when it actually waits on `cvar`. If we were to notify
243 // during this period it would be ignored and then when the parked
244 // thread went to sleep it would never wake up. Fortunately, it has
245 // `lock` locked at this stage so we can acquire `lock` to wait until
246 // it is ready to receive the notification.
248 // Releasing `lock` before the call to `notify_one` means that when the
249 // parked thread wakes it doesn't get woken only to have to wait for us
250 // to release `lock`.
252 lock(self.lock.get());
253 unlock(self.lock.get());
254 notify_one(self.cvar.get());
259 impl Drop for Parker {
262 libc::pthread_cond_destroy(self.cvar.get_mut());
263 libc::pthread_mutex_destroy(self.lock.get_mut());
268 unsafe impl Sync for Parker {}
269 unsafe impl Send for Parker {}