]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/condvar.rs
Rollup merge of #84320 - jsha:details-implementors, r=Manishearth,Nemo157,GuillaumeGomez
[rust.git] / library / std / src / sys / unix / condvar.rs
1 use crate::cell::UnsafeCell;
2 use crate::sys::mutex::{self, Mutex};
3 use crate::time::Duration;
4
5 pub struct Condvar {
6     inner: UnsafeCell<libc::pthread_cond_t>,
7 }
8
9 pub type MovableCondvar = Box<Condvar>;
10
11 unsafe impl Send for Condvar {}
12 unsafe impl Sync for Condvar {}
13
14 const TIMESPEC_MAX: libc::timespec =
15     libc::timespec { tv_sec: <libc::time_t>::MAX, tv_nsec: 1_000_000_000 - 1 };
16
17 fn saturating_cast_to_time_t(value: u64) -> libc::time_t {
18     if value > <libc::time_t>::MAX as u64 { <libc::time_t>::MAX } else { value as libc::time_t }
19 }
20
21 impl Condvar {
22     pub const fn new() -> Condvar {
23         // Might be moved and address is changing it is better to avoid
24         // initialization of potentially opaque OS data before it landed
25         Condvar { inner: UnsafeCell::new(libc::PTHREAD_COND_INITIALIZER) }
26     }
27
28     #[cfg(any(
29         target_os = "macos",
30         target_os = "ios",
31         target_os = "l4re",
32         target_os = "android",
33         target_os = "redox"
34     ))]
35     pub unsafe fn init(&mut self) {}
36
37     #[cfg(not(any(
38         target_os = "macos",
39         target_os = "ios",
40         target_os = "l4re",
41         target_os = "android",
42         target_os = "redox"
43     )))]
44     pub unsafe fn init(&mut self) {
45         use crate::mem::MaybeUninit;
46         let mut attr = MaybeUninit::<libc::pthread_condattr_t>::uninit();
47         let r = libc::pthread_condattr_init(attr.as_mut_ptr());
48         assert_eq!(r, 0);
49         let r = libc::pthread_condattr_setclock(attr.as_mut_ptr(), libc::CLOCK_MONOTONIC);
50         assert_eq!(r, 0);
51         let r = libc::pthread_cond_init(self.inner.get(), attr.as_ptr());
52         assert_eq!(r, 0);
53         let r = libc::pthread_condattr_destroy(attr.as_mut_ptr());
54         assert_eq!(r, 0);
55     }
56
57     #[inline]
58     pub unsafe fn notify_one(&self) {
59         let r = libc::pthread_cond_signal(self.inner.get());
60         debug_assert_eq!(r, 0);
61     }
62
63     #[inline]
64     pub unsafe fn notify_all(&self) {
65         let r = libc::pthread_cond_broadcast(self.inner.get());
66         debug_assert_eq!(r, 0);
67     }
68
69     #[inline]
70     pub unsafe fn wait(&self, mutex: &Mutex) {
71         let r = libc::pthread_cond_wait(self.inner.get(), mutex::raw(mutex));
72         debug_assert_eq!(r, 0);
73     }
74
75     // This implementation is used on systems that support pthread_condattr_setclock
76     // where we configure condition variable to use monotonic clock (instead of
77     // default system clock). This approach avoids all problems that result
78     // from changes made to the system time.
79     #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "android")))]
80     pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
81         use crate::mem;
82
83         let mut now: libc::timespec = mem::zeroed();
84         let r = libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut now);
85         assert_eq!(r, 0);
86
87         // Nanosecond calculations can't overflow because both values are below 1e9.
88         let nsec = dur.subsec_nanos() + now.tv_nsec as u32;
89
90         let sec = saturating_cast_to_time_t(dur.as_secs())
91             .checked_add((nsec / 1_000_000_000) as libc::time_t)
92             .and_then(|s| s.checked_add(now.tv_sec));
93         let nsec = nsec % 1_000_000_000;
94
95         let timeout =
96             sec.map(|s| libc::timespec { tv_sec: s, tv_nsec: nsec as _ }).unwrap_or(TIMESPEC_MAX);
97
98         let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex), &timeout);
99         assert!(r == libc::ETIMEDOUT || r == 0);
100         r == 0
101     }
102
103     // This implementation is modeled after libcxx's condition_variable
104     // https://github.com/llvm-mirror/libcxx/blob/release_35/src/condition_variable.cpp#L46
105     // https://github.com/llvm-mirror/libcxx/blob/release_35/include/__mutex_base#L367
106     #[cfg(any(target_os = "macos", target_os = "ios", target_os = "android"))]
107     pub unsafe fn wait_timeout(&self, mutex: &Mutex, mut dur: Duration) -> bool {
108         use crate::ptr;
109         use crate::time::Instant;
110
111         // 1000 years
112         let max_dur = Duration::from_secs(1000 * 365 * 86400);
113
114         if dur > max_dur {
115             // OSX implementation of `pthread_cond_timedwait` is buggy
116             // with super long durations. When duration is greater than
117             // 0x100_0000_0000_0000 seconds, `pthread_cond_timedwait`
118             // in macOS Sierra return error 316.
119             //
120             // This program demonstrates the issue:
121             // https://gist.github.com/stepancheg/198db4623a20aad2ad7cddb8fda4a63c
122             //
123             // To work around this issue, and possible bugs of other OSes, timeout
124             // is clamped to 1000 years, which is allowable per the API of `wait_timeout`
125             // because of spurious wakeups.
126
127             dur = max_dur;
128         }
129
130         // First, figure out what time it currently is, in both system and
131         // stable time.  pthread_cond_timedwait uses system time, but we want to
132         // report timeout based on stable time.
133         let mut sys_now = libc::timeval { tv_sec: 0, tv_usec: 0 };
134         let stable_now = Instant::now();
135         let r = libc::gettimeofday(&mut sys_now, ptr::null_mut());
136         debug_assert_eq!(r, 0);
137
138         let nsec = dur.subsec_nanos() as libc::c_long + (sys_now.tv_usec * 1000) as libc::c_long;
139         let extra = (nsec / 1_000_000_000) as libc::time_t;
140         let nsec = nsec % 1_000_000_000;
141         let seconds = saturating_cast_to_time_t(dur.as_secs());
142
143         let timeout = sys_now
144             .tv_sec
145             .checked_add(extra)
146             .and_then(|s| s.checked_add(seconds))
147             .map(|s| libc::timespec { tv_sec: s, tv_nsec: nsec })
148             .unwrap_or(TIMESPEC_MAX);
149
150         // And wait!
151         let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex), &timeout);
152         debug_assert!(r == libc::ETIMEDOUT || r == 0);
153
154         // ETIMEDOUT is not a totally reliable method of determining timeout due
155         // to clock shifts, so do the check ourselves
156         stable_now.elapsed() < dur
157     }
158
159     #[inline]
160     #[cfg(not(target_os = "dragonfly"))]
161     pub unsafe fn destroy(&self) {
162         let r = libc::pthread_cond_destroy(self.inner.get());
163         debug_assert_eq!(r, 0);
164     }
165
166     #[inline]
167     #[cfg(target_os = "dragonfly")]
168     pub unsafe fn destroy(&self) {
169         let r = libc::pthread_cond_destroy(self.inner.get());
170         // On DragonFly pthread_cond_destroy() returns EINVAL if called on
171         // a condvar that was just initialized with
172         // libc::PTHREAD_COND_INITIALIZER. Once it is used or
173         // pthread_cond_init() is called, this behaviour no longer occurs.
174         debug_assert!(r == 0 || r == libc::EINVAL);
175     }
176 }