std/sys/pal/unix/sync/condvar.rs
1use super::Mutex;
2use crate::cell::UnsafeCell;
3use crate::pin::Pin;
4#[cfg(not(target_os = "nto"))]
5use crate::sys::pal::time::TIMESPEC_MAX;
6#[cfg(target_os = "nto")]
7use crate::sys::pal::time::TIMESPEC_MAX_CAPPED;
8use crate::time::Duration;
9
10pub struct Condvar {
11 inner: UnsafeCell<libc::pthread_cond_t>,
12}
13
14impl Condvar {
15 pub fn new() -> Condvar {
16 Condvar { inner: UnsafeCell::new(libc::PTHREAD_COND_INITIALIZER) }
17 }
18
19 #[inline]
20 fn raw(&self) -> *mut libc::pthread_cond_t {
21 self.inner.get()
22 }
23
24 /// # Safety
25 /// `init` must have been called on this instance.
26 #[inline]
27 pub unsafe fn notify_one(self: Pin<&Self>) {
28 let r = unsafe { libc::pthread_cond_signal(self.raw()) };
29 debug_assert_eq!(r, 0);
30 }
31
32 /// # Safety
33 /// `init` must have been called on this instance.
34 #[inline]
35 pub unsafe fn notify_all(self: Pin<&Self>) {
36 let r = unsafe { libc::pthread_cond_broadcast(self.raw()) };
37 debug_assert_eq!(r, 0);
38 }
39
40 /// # Safety
41 /// * `init` must have been called on this instance.
42 /// * `mutex` must be locked by the current thread.
43 /// * This condition variable may only be used with the same mutex.
44 #[inline]
45 pub unsafe fn wait(self: Pin<&Self>, mutex: Pin<&Mutex>) {
46 let r = unsafe { libc::pthread_cond_wait(self.raw(), mutex.raw()) };
47 debug_assert_eq!(r, 0);
48 }
49}
50
51#[cfg(not(target_vendor = "apple"))]
52impl Condvar {
53 /// # Safety
54 /// * `init` must have been called on this instance.
55 /// * `mutex` must be locked by the current thread.
56 /// * This condition variable may only be used with the same mutex.
57 pub unsafe fn wait_timeout(&self, mutex: Pin<&Mutex>, dur: Duration) -> bool {
58 use crate::sys::pal::time::Timespec;
59
60 let mutex = mutex.raw();
61
62 // Cygwin's implementation is based on the NT API, which measures time
63 // in units of 100 ns. Unfortunately, Cygwin does not properly guard
64 // against overflow when converting the time, hence we clamp the interval
65 // to 1000 years, which will only become a problem in around 27000 years,
66 // when the next rollover is less than 1000 years away...
67 #[cfg(target_os = "cygwin")]
68 let dur = Duration::min(dur, Duration::from_secs(1000 * 365 * 86400));
69
70 let timeout = Timespec::now(Self::CLOCK).checked_add_duration(&dur);
71
72 #[cfg(not(target_os = "nto"))]
73 let timeout = timeout.and_then(|t| t.to_timespec()).unwrap_or(TIMESPEC_MAX);
74
75 #[cfg(target_os = "nto")]
76 let timeout = timeout.and_then(|t| t.to_timespec_capped()).unwrap_or(TIMESPEC_MAX_CAPPED);
77
78 let r = unsafe { libc::pthread_cond_timedwait(self.raw(), mutex, &timeout) };
79 assert!(r == libc::ETIMEDOUT || r == 0);
80 r == 0
81 }
82}
83
84// Apple platforms (since macOS version 10.4 and iOS version 2.0) have
85// `pthread_cond_timedwait_relative_np`, a non-standard extension that
86// measures timeouts based on the monotonic clock and is thus resilient
87// against wall-clock changes.
88#[cfg(target_vendor = "apple")]
89impl Condvar {
90 /// # Safety
91 /// * `init` must have been called on this instance.
92 /// * `mutex` must be locked by the current thread.
93 /// * This condition variable may only be used with the same mutex.
94 pub unsafe fn wait_timeout(&self, mutex: Pin<&Mutex>, dur: Duration) -> bool {
95 let mutex = mutex.raw();
96
97 // The macOS implementation of `pthread_cond_timedwait` internally
98 // converts the timeout passed to `pthread_cond_timedwait_relative_np`
99 // to nanoseconds. Unfortunately, the "psynch" variant of condvars does
100 // not guard against overflow during the conversion[^1], which means
101 // that `pthread_cond_timedwait_relative_np` will return `ETIMEDOUT`
102 // much earlier than expected if the relative timeout is longer than
103 // `u64::MAX` nanoseconds.
104 //
105 // This can be observed even on newer platforms (by setting the environment
106 // variable PTHREAD_MUTEX_USE_ULOCK to a value other than "1") by calling e.g.
107 // ```
108 // condvar.wait_timeout(..., Duration::from_secs(u64::MAX.div_ceil(1_000_000_000));
109 // ```
110 // (see #37440, especially
111 // https://github.com/rust-lang/rust/issues/37440#issuecomment-3285958326).
112 //
113 // To work around this issue, always clamp the timeout to u64::MAX nanoseconds,
114 // even if the "ulock" variant is used (which does guard against overflow).
115 //
116 // [^1]: https://github.com/apple-oss-distributions/libpthread/blob/1ebf56b3a702df53213c2996e5e128a535d2577e/kern/kern_synch.c#L1269
117 const MAX_DURATION: Duration = Duration::from_nanos(u64::MAX);
118
119 let (dur, clamped) = if dur <= MAX_DURATION { (dur, false) } else { (MAX_DURATION, true) };
120
121 // This can overflow on 32-bit platforms, but not on 64-bit because of the clamping above.
122 let timeout = if let Ok(tv_sec) = dur.as_secs().try_into() {
123 libc::timespec { tv_sec, tv_nsec: dur.subsec_nanos() as _ }
124 } else {
125 // This is less than `MAX_DURATION` on 32-bit platforms.
126 TIMESPEC_MAX
127 };
128
129 let r = unsafe { libc::pthread_cond_timedwait_relative_np(self.raw(), mutex, &timeout) };
130 assert!(r == libc::ETIMEDOUT || r == 0);
131 // Report clamping as a spurious wakeup. Who knows, maybe some
132 // interstellar space probe will rely on this ;-).
133 r == 0 || clamped
134 }
135}
136
137#[cfg(not(any(
138 target_os = "android",
139 target_vendor = "apple",
140 target_os = "espidf",
141 target_os = "horizon",
142 target_os = "l4re",
143 target_os = "redox",
144 target_os = "teeos",
145)))]
146impl Condvar {
147 pub const PRECISE_TIMEOUT: bool = true;
148 const CLOCK: libc::clockid_t = libc::CLOCK_MONOTONIC;
149
150 /// # Safety
151 /// May only be called once per instance of `Self`.
152 pub unsafe fn init(self: Pin<&mut Self>) {
153 use crate::mem::MaybeUninit;
154
155 struct AttrGuard<'a>(pub &'a mut MaybeUninit<libc::pthread_condattr_t>);
156 impl Drop for AttrGuard<'_> {
157 fn drop(&mut self) {
158 unsafe {
159 let result = libc::pthread_condattr_destroy(self.0.as_mut_ptr());
160 assert_eq!(result, 0);
161 }
162 }
163 }
164
165 unsafe {
166 let mut attr = MaybeUninit::<libc::pthread_condattr_t>::uninit();
167 let r = libc::pthread_condattr_init(attr.as_mut_ptr());
168 assert_eq!(r, 0);
169 let attr = AttrGuard(&mut attr);
170 let r = libc::pthread_condattr_setclock(attr.0.as_mut_ptr(), Self::CLOCK);
171 assert_eq!(r, 0);
172 let r = libc::pthread_cond_init(self.raw(), attr.0.as_ptr());
173 assert_eq!(r, 0);
174 }
175 }
176}
177
178#[cfg(target_vendor = "apple")]
179impl Condvar {
180 // `pthread_cond_timedwait_relative_np` measures the timeout
181 // based on the monotonic clock.
182 pub const PRECISE_TIMEOUT: bool = true;
183
184 /// # Safety
185 /// May only be called once per instance of `Self`.
186 pub unsafe fn init(self: Pin<&mut Self>) {
187 // `PTHREAD_COND_INITIALIZER` is fully supported and we don't need to
188 // change clocks, so there's nothing to do here.
189 }
190}
191
192// `pthread_condattr_setclock` is unfortunately not supported on these platforms.
193#[cfg(any(
194 target_os = "android",
195 target_os = "espidf",
196 target_os = "horizon",
197 target_os = "l4re",
198 target_os = "redox",
199 target_os = "teeos",
200))]
201impl Condvar {
202 pub const PRECISE_TIMEOUT: bool = false;
203 const CLOCK: libc::clockid_t = libc::CLOCK_REALTIME;
204
205 /// # Safety
206 /// May only be called once per instance of `Self`.
207 pub unsafe fn init(self: Pin<&mut Self>) {
208 if cfg!(any(target_os = "espidf", target_os = "horizon", target_os = "teeos")) {
209 // NOTE: ESP-IDF's PTHREAD_COND_INITIALIZER support is not released yet
210 // So on that platform, init() should always be called.
211 //
212 // Similar story for the 3DS (horizon) and for TEEOS.
213 let r = unsafe { libc::pthread_cond_init(self.raw(), crate::ptr::null()) };
214 assert_eq!(r, 0);
215 }
216 }
217}
218
219impl !Unpin for Condvar {}
220
221unsafe impl Sync for Condvar {}
222unsafe impl Send for Condvar {}
223
224impl Drop for Condvar {
225 #[inline]
226 fn drop(&mut self) {
227 let r = unsafe { libc::pthread_cond_destroy(self.raw()) };
228 if cfg!(target_os = "dragonfly") {
229 // On DragonFly pthread_cond_destroy() returns EINVAL if called on
230 // a condvar that was just initialized with
231 // libc::PTHREAD_COND_INITIALIZER. Once it is used or
232 // pthread_cond_init() is called, this behaviour no longer occurs.
233 debug_assert!(r == 0 || r == libc::EINVAL);
234 } else {
235 debug_assert_eq!(r, 0);
236 }
237 }
238}