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