]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/thread_parker/pthread.rs
Rollup merge of #103718 - matklad:infer-lazy, r=dtolnay
[rust.git] / library / std / src / sys / unix / thread_parker / pthread.rs
1 //! Thread parking without `futex` using the `pthread` synchronization primitives.
2
3 use crate::cell::UnsafeCell;
4 use crate::marker::PhantomPinned;
5 use crate::pin::Pin;
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;
11
12 const EMPTY: usize = 0;
13 const PARKED: usize = 1;
14 const NOTIFIED: usize = 2;
15
16 unsafe fn lock(lock: *mut libc::pthread_mutex_t) {
17     let r = libc::pthread_mutex_lock(lock);
18     debug_assert_eq!(r, 0);
19 }
20
21 unsafe fn unlock(lock: *mut libc::pthread_mutex_t) {
22     let r = libc::pthread_mutex_unlock(lock);
23     debug_assert_eq!(r, 0);
24 }
25
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);
29 }
30
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);
34 }
35
36 unsafe fn wait_timeout(
37     cond: *mut libc::pthread_cond_t,
38     lock: *mut libc::pthread_mutex_t,
39     dur: Duration,
40 ) {
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.
43     #[cfg(any(
44         target_os = "macos",
45         target_os = "ios",
46         target_os = "watchos",
47         target_os = "espidf"
48     ))]
49     let (now, dur) = {
50         use crate::cmp::min;
51         use crate::sys::time::SystemTime;
52
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.
57         //
58         // This program demonstrates the issue:
59         // https://gist.github.com/stepancheg/198db4623a20aad2ad7cddb8fda4a63c
60         //
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;
66         (now, dur)
67     };
68     // Use the monotonic clock on other systems.
69     #[cfg(not(any(
70         target_os = "macos",
71         target_os = "ios",
72         target_os = "watchos",
73         target_os = "espidf"
74     )))]
75     let (now, dur) = {
76         use crate::sys::time::Timespec;
77
78         (Timespec::now(libc::CLOCK_MONOTONIC), dur)
79     };
80
81     let timeout =
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);
85 }
86
87 pub struct Parker {
88     state: AtomicUsize,
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,
93 }
94
95 impl Parker {
96     /// Construct the UNIX parker in-place.
97     ///
98     /// # Safety
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));
107
108         cfg_if::cfg_if! {
109             if #[cfg(any(
110                 target_os = "macos",
111                 target_os = "ios",
112                 target_os = "watchos",
113                 target_os = "l4re",
114                 target_os = "android",
115                 target_os = "redox"
116             ))] {
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());
120                 assert_eq!(r, 0);
121             } else {
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());
125                 assert_eq!(r, 0);
126                 let r = libc::pthread_condattr_setclock(attr.as_mut_ptr(), libc::CLOCK_MONOTONIC);
127                 assert_eq!(r, 0);
128                 let r = libc::pthread_cond_init(addr_of_mut!((*parker).cvar).cast(), attr.as_ptr());
129                 assert_eq!(r, 0);
130                 let r = libc::pthread_condattr_destroy(attr.as_mut_ptr());
131                 assert_eq!(r, 0);
132             }
133         }
134     }
135
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
140         // return quickly.
141         if self.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst).is_ok() {
142             return;
143         }
144
145         // Otherwise we need to coordinate going to sleep
146         lock(self.lock.get());
147         match self.state.compare_exchange(EMPTY, PARKED, SeqCst, SeqCst) {
148             Ok(_) => {}
149             Err(NOTIFIED) => {
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);
157
158                 unlock(self.lock.get());
159
160                 assert_eq!(old, NOTIFIED, "park state changed unexpectedly");
161                 return;
162             } // should consume this notification, so prohibit spurious wakeups in next park.
163             Err(_) => {
164                 unlock(self.lock.get());
165
166                 panic!("inconsistent park state")
167             }
168         }
169
170         loop {
171             wait(self.cvar.get(), self.lock.get());
172
173             match self.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst) {
174                 Ok(_) => break, // got a notification
175                 Err(_) => {}    // spurious wakeup, go back to sleep
176             }
177         }
178
179         unlock(self.lock.get());
180     }
181
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.
188         // return quickly.
189         if self.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst).is_ok() {
190             return;
191         }
192
193         lock(self.lock.get());
194         match self.state.compare_exchange(EMPTY, PARKED, SeqCst, SeqCst) {
195             Ok(_) => {}
196             Err(NOTIFIED) => {
197                 // We must read again here, see `park`.
198                 let old = self.state.swap(EMPTY, SeqCst);
199                 unlock(self.lock.get());
200
201                 assert_eq!(old, NOTIFIED, "park state changed unexpectedly");
202                 return;
203             } // should consume this notification, so prohibit spurious wakeups in next park.
204             Err(_) => {
205                 unlock(self.lock.get());
206                 panic!("inconsistent park_timeout state")
207             }
208         }
209
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
213         // parked.
214         wait_timeout(self.cvar.get(), self.lock.get(), dur);
215
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
219             n => {
220                 unlock(self.lock.get());
221                 panic!("inconsistent park_timeout state: {n}")
222             }
223         }
224     }
225
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`
232         // on failure.
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"),
238         }
239
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.
247         //
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`.
251         unsafe {
252             lock(self.lock.get());
253             unlock(self.lock.get());
254             notify_one(self.cvar.get());
255         }
256     }
257 }
258
259 impl Drop for Parker {
260     fn drop(&mut self) {
261         unsafe {
262             libc::pthread_cond_destroy(self.cvar.get_mut());
263             libc::pthread_mutex_destroy(self.lock.get_mut());
264         }
265     }
266 }
267
268 unsafe impl Sync for Parker {}
269 unsafe impl Send for Parker {}