Skip to main content

std/sys/pal/unix/sync/
condvar.rs

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