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::sys::pal::time::Timespec;
9use crate::time::Duration;
10
11pub struct Condvar {
12    inner: UnsafeCell<libc::pthread_cond_t>,
13}
14
15impl Condvar {
16    pub fn new() -> Condvar {
17        Condvar { inner: UnsafeCell::new(libc::PTHREAD_COND_INITIALIZER) }
18    }
19
20    #[inline]
21    fn raw(&self) -> *mut libc::pthread_cond_t {
22        self.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    /// # Safety
52    /// * `init` must have been called on this instance.
53    /// * `mutex` must be locked by the current thread.
54    /// * This condition variable may only be used with the same mutex.
55    pub unsafe fn wait_timeout(&self, mutex: Pin<&Mutex>, dur: Duration) -> bool {
56        let mutex = mutex.raw();
57
58        // OSX implementation of `pthread_cond_timedwait` is buggy
59        // with super long durations. When duration is greater than
60        // 0x100_0000_0000_0000 seconds, `pthread_cond_timedwait`
61        // in macOS Sierra returns error 316.
62        //
63        // This program demonstrates the issue:
64        // https://gist.github.com/stepancheg/198db4623a20aad2ad7cddb8fda4a63c
65        //
66        // To work around this issue, the timeout is clamped to 1000 years.
67        //
68        // Cygwin implementation is based on NT API and a super large timeout
69        // makes the syscall block forever.
70        #[cfg(any(target_vendor = "apple", target_os = "cygwin"))]
71        let dur = Duration::min(dur, Duration::from_secs(1000 * 365 * 86400));
72
73        let timeout = Timespec::now(Self::CLOCK).checked_add_duration(&dur);
74
75        #[cfg(not(target_os = "nto"))]
76        let timeout = timeout.and_then(|t| t.to_timespec()).unwrap_or(TIMESPEC_MAX);
77
78        #[cfg(target_os = "nto")]
79        let timeout = timeout.and_then(|t| t.to_timespec_capped()).unwrap_or(TIMESPEC_MAX_CAPPED);
80
81        let r = unsafe { libc::pthread_cond_timedwait(self.raw(), mutex, &timeout) };
82        assert!(r == libc::ETIMEDOUT || r == 0);
83        r == 0
84    }
85}
86
87#[cfg(not(any(
88    target_os = "android",
89    target_vendor = "apple",
90    target_os = "espidf",
91    target_os = "horizon",
92    target_os = "l4re",
93    target_os = "redox",
94    target_os = "teeos",
95)))]
96impl Condvar {
97    pub const PRECISE_TIMEOUT: bool = true;
98    const CLOCK: libc::clockid_t = libc::CLOCK_MONOTONIC;
99
100    /// # Safety
101    /// May only be called once per instance of `Self`.
102    pub unsafe fn init(self: Pin<&mut Self>) {
103        use crate::mem::MaybeUninit;
104
105        struct AttrGuard<'a>(pub &'a mut MaybeUninit<libc::pthread_condattr_t>);
106        impl Drop for AttrGuard<'_> {
107            fn drop(&mut self) {
108                unsafe {
109                    let result = libc::pthread_condattr_destroy(self.0.as_mut_ptr());
110                    assert_eq!(result, 0);
111                }
112            }
113        }
114
115        unsafe {
116            let mut attr = MaybeUninit::<libc::pthread_condattr_t>::uninit();
117            let r = libc::pthread_condattr_init(attr.as_mut_ptr());
118            assert_eq!(r, 0);
119            let attr = AttrGuard(&mut attr);
120            let r = libc::pthread_condattr_setclock(attr.0.as_mut_ptr(), Self::CLOCK);
121            assert_eq!(r, 0);
122            let r = libc::pthread_cond_init(self.raw(), attr.0.as_ptr());
123            assert_eq!(r, 0);
124        }
125    }
126}
127
128// `pthread_condattr_setclock` is unfortunately not supported on these platforms.
129#[cfg(any(
130    target_os = "android",
131    target_vendor = "apple",
132    target_os = "espidf",
133    target_os = "horizon",
134    target_os = "l4re",
135    target_os = "redox",
136    target_os = "teeos",
137))]
138impl Condvar {
139    pub const PRECISE_TIMEOUT: bool = false;
140    const CLOCK: libc::clockid_t = libc::CLOCK_REALTIME;
141
142    /// # Safety
143    /// May only be called once per instance of `Self`.
144    pub unsafe fn init(self: Pin<&mut Self>) {
145        if cfg!(any(target_os = "espidf", target_os = "horizon", target_os = "teeos")) {
146            // NOTE: ESP-IDF's PTHREAD_COND_INITIALIZER support is not released yet
147            // So on that platform, init() should always be called.
148            //
149            // Similar story for the 3DS (horizon) and for TEEOS.
150            let r = unsafe { libc::pthread_cond_init(self.raw(), crate::ptr::null()) };
151            assert_eq!(r, 0);
152        }
153    }
154}
155
156impl !Unpin for Condvar {}
157
158unsafe impl Sync for Condvar {}
159unsafe impl Send for Condvar {}
160
161impl Drop for Condvar {
162    #[inline]
163    fn drop(&mut self) {
164        let r = unsafe { libc::pthread_cond_destroy(self.raw()) };
165        if cfg!(target_os = "dragonfly") {
166            // On DragonFly pthread_cond_destroy() returns EINVAL if called on
167            // a condvar that was just initialized with
168            // libc::PTHREAD_COND_INITIALIZER. Once it is used or
169            // pthread_cond_init() is called, this behaviour no longer occurs.
170            debug_assert!(r == 0 || r == libc::EINVAL);
171        } else {
172            debug_assert_eq!(r, 0);
173        }
174    }
175}