]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/condvar.rs
Rollup merge of #63630 - andjo403:bump_compiler, r=nikomatsakis
[rust.git] / src / libstd / 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 { inner: UnsafeCell<libc::pthread_cond_t> }
6
7 unsafe impl Send for Condvar {}
8 unsafe impl Sync for Condvar {}
9
10 const TIMESPEC_MAX: libc::timespec = libc::timespec {
11     tv_sec: <libc::time_t>::max_value(),
12     tv_nsec: 1_000_000_000 - 1,
13 };
14
15 fn saturating_cast_to_time_t(value: u64) -> libc::time_t {
16     if value > <libc::time_t>::max_value() as u64 {
17         <libc::time_t>::max_value()
18     } else {
19         value as libc::time_t
20     }
21 }
22
23 impl Condvar {
24     pub const fn new() -> Condvar {
25         // Might be moved and address is changing it is better to avoid
26         // initialization of potentially opaque OS data before it landed
27         Condvar { inner: UnsafeCell::new(libc::PTHREAD_COND_INITIALIZER) }
28     }
29
30     #[cfg(any(target_os = "macos",
31               target_os = "ios",
32               target_os = "l4re",
33               target_os = "android",
34               target_os = "hermit",
35               target_os = "redox"))]
36     pub unsafe fn init(&mut self) {}
37
38     #[cfg(not(any(target_os = "macos",
39                   target_os = "ios",
40                   target_os = "l4re",
41                   target_os = "android",
42                   target_os = "hermit",
43                   target_os = "redox")))]
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",
80                   target_os = "ios",
81                   target_os = "android",
82                   target_os = "hermit")))]
83     pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
84         use crate::mem;
85
86         let mut now: libc::timespec = mem::zeroed();
87         let r = libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut now);
88         assert_eq!(r, 0);
89
90         // Nanosecond calculations can't overflow because both values are below 1e9.
91         let nsec = dur.subsec_nanos() + now.tv_nsec as u32;
92
93         let sec = saturating_cast_to_time_t(dur.as_secs())
94             .checked_add((nsec / 1_000_000_000) as libc::time_t)
95             .and_then(|s| s.checked_add(now.tv_sec));
96         let nsec = nsec % 1_000_000_000;
97
98         let timeout = sec.map(|s| {
99             libc::timespec { tv_sec: s, tv_nsec: nsec as _}
100         }).unwrap_or(TIMESPEC_MAX);
101
102         let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex),
103                                             &timeout);
104         assert!(r == libc::ETIMEDOUT || r == 0);
105         r == 0
106     }
107
108
109     // This implementation is modeled after libcxx's condition_variable
110     // https://github.com/llvm-mirror/libcxx/blob/release_35/src/condition_variable.cpp#L46
111     // https://github.com/llvm-mirror/libcxx/blob/release_35/include/__mutex_base#L367
112     #[cfg(any(target_os = "macos", target_os = "ios", target_os = "android", target_os = "hermit"))]
113     pub unsafe fn wait_timeout(&self, mutex: &Mutex, mut dur: Duration) -> bool {
114         use crate::ptr;
115         use crate::time::Instant;
116
117         // 1000 years
118         let max_dur = Duration::from_secs(1000 * 365 * 86400);
119
120         if dur > max_dur {
121             // OSX implementation of `pthread_cond_timedwait` is buggy
122             // with super long durations. When duration is greater than
123             // 0x100_0000_0000_0000 seconds, `pthread_cond_timedwait`
124             // in macOS Sierra return error 316.
125             //
126             // This program demonstrates the issue:
127             // https://gist.github.com/stepancheg/198db4623a20aad2ad7cddb8fda4a63c
128             //
129             // To work around this issue, and possible bugs of other OSes, timeout
130             // is clamped to 1000 years, which is allowable per the API of `wait_timeout`
131             // because of spurious wakeups.
132
133             dur = max_dur;
134         }
135
136         // First, figure out what time it currently is, in both system and
137         // stable time.  pthread_cond_timedwait uses system time, but we want to
138         // report timeout based on stable time.
139         let mut sys_now = libc::timeval { tv_sec: 0, tv_usec: 0 };
140         let stable_now = Instant::now();
141         let r = libc::gettimeofday(&mut sys_now, ptr::null_mut());
142         debug_assert_eq!(r, 0);
143
144         let nsec = dur.subsec_nanos() as libc::c_long +
145                    (sys_now.tv_usec * 1000) as libc::c_long;
146         let extra = (nsec / 1_000_000_000) as libc::time_t;
147         let nsec = nsec % 1_000_000_000;
148         let seconds = saturating_cast_to_time_t(dur.as_secs());
149
150         let timeout = sys_now.tv_sec.checked_add(extra).and_then(|s| {
151             s.checked_add(seconds)
152         }).map(|s| {
153             libc::timespec { tv_sec: s, tv_nsec: nsec }
154         }).unwrap_or(TIMESPEC_MAX);
155
156         // And wait!
157         let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex),
158                                             &timeout);
159         debug_assert!(r == libc::ETIMEDOUT || r == 0);
160
161         // ETIMEDOUT is not a totally reliable method of determining timeout due
162         // to clock shifts, so do the check ourselves
163         stable_now.elapsed() < dur
164     }
165
166     #[inline]
167     #[cfg(not(target_os = "dragonfly"))]
168     pub unsafe fn destroy(&self) {
169         let r = libc::pthread_cond_destroy(self.inner.get());
170         debug_assert_eq!(r, 0);
171     }
172
173     #[inline]
174     #[cfg(target_os = "dragonfly")]
175     pub unsafe fn destroy(&self) {
176         let r = libc::pthread_cond_destroy(self.inner.get());
177         // On DragonFly pthread_cond_destroy() returns EINVAL if called on
178         // a condvar that was just initialized with
179         // libc::PTHREAD_COND_INITIALIZER. Once it is used or
180         // pthread_cond_init() is called, this behaviour no longer occurs.
181         debug_assert!(r == 0 || r == libc::EINVAL);
182     }
183 }