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