1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 use sync::atomic::{AtomicUsize, Ordering};
14 use sync::{mutex, MutexGuard, PoisonError};
15 use sys_common::condvar as sys;
16 use sys_common::mutex as sys_mutex;
17 use sys_common::poison::{self, LockResult};
18 use time::{Instant, Duration};
20 /// A type indicating whether a timed wait on a condition variable returned
21 /// due to a time out or not.
22 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
23 #[stable(feature = "wait_timeout", since = "1.5.0")]
24 pub struct WaitTimeoutResult(bool);
26 impl WaitTimeoutResult {
27 /// Returns whether the wait was known to have timed out.
28 #[stable(feature = "wait_timeout", since = "1.5.0")]
29 pub fn timed_out(&self) -> bool {
34 /// A Condition Variable
36 /// Condition variables represent the ability to block a thread such that it
37 /// consumes no CPU time while waiting for an event to occur. Condition
38 /// variables are typically associated with a boolean predicate (a condition)
39 /// and a mutex. The predicate is always verified inside of the mutex before
40 /// determining that thread must block.
42 /// Functions in this module will block the current **thread** of execution and
43 /// are bindings to system-provided condition variables where possible. Note
44 /// that this module places one additional restriction over the system condition
45 /// variables: each condvar can be used with precisely one mutex at runtime. Any
46 /// attempt to use multiple mutexes on the same condition variable will result
47 /// in a runtime panic. If this is not desired, then the unsafe primitives in
48 /// `sys` do not have this restriction but may result in undefined behavior.
53 /// use std::sync::{Arc, Mutex, Condvar};
56 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
57 /// let pair2 = pair.clone();
59 /// // Inside of our lock, spawn a new thread, and then wait for it to start
60 /// thread::spawn(move|| {
61 /// let &(ref lock, ref cvar) = &*pair2;
62 /// let mut started = lock.lock().unwrap();
64 /// cvar.notify_one();
67 /// // wait for the thread to start up
68 /// let &(ref lock, ref cvar) = &*pair;
69 /// let mut started = lock.lock().unwrap();
71 /// started = cvar.wait(started).unwrap();
74 #[stable(feature = "rust1", since = "1.0.0")]
75 pub struct Condvar { inner: Box<StaticCondvar> }
77 /// Statically allocated condition variables.
79 /// This structure is identical to `Condvar` except that it is suitable for use
80 /// in static initializers for other structures.
85 /// #![feature(static_condvar)]
87 /// use std::sync::{StaticCondvar, CONDVAR_INIT};
89 /// static CVAR: StaticCondvar = CONDVAR_INIT;
91 #[unstable(feature = "static_condvar",
92 reason = "may be merged with Condvar in the future",
94 pub struct StaticCondvar {
99 /// Constant initializer for a statically allocated condition variable.
100 #[unstable(feature = "static_condvar",
101 reason = "may be merged with Condvar in the future",
103 pub const CONDVAR_INIT: StaticCondvar = StaticCondvar::new();
106 /// Creates a new condition variable which is ready to be waited on and
108 #[stable(feature = "rust1", since = "1.0.0")]
109 pub fn new() -> Condvar {
111 inner: box StaticCondvar {
112 inner: sys::Condvar::new(),
113 mutex: AtomicUsize::new(0),
118 /// Blocks the current thread until this condition variable receives a
121 /// This function will atomically unlock the mutex specified (represented by
122 /// `mutex_guard`) and block the current thread. This means that any calls
123 /// to `notify_*()` which happen logically after the mutex is unlocked are
124 /// candidates to wake this thread up. When this function call returns, the
125 /// lock specified will have been re-acquired.
127 /// Note that this function is susceptible to spurious wakeups. Condition
128 /// variables normally have a boolean predicate associated with them, and
129 /// the predicate must always be checked each time this function returns to
130 /// protect against spurious wakeups.
134 /// This function will return an error if the mutex being waited on is
135 /// poisoned when this thread re-acquires the lock. For more information,
136 /// see information about poisoning on the Mutex type.
140 /// This function will `panic!()` if it is used with more than one mutex
141 /// over time. Each condition variable is dynamically bound to exactly one
142 /// mutex to ensure defined behavior across platforms. If this functionality
143 /// is not desired, then unsafe primitives in `sys` are provided.
144 #[stable(feature = "rust1", since = "1.0.0")]
145 pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>)
146 -> LockResult<MutexGuard<'a, T>> {
148 let me: &'static Condvar = &*(self as *const _);
153 /// Waits on this condition variable for a notification, timing out after a
154 /// specified duration.
156 /// The semantics of this function are equivalent to `wait()`
157 /// except that the thread will be blocked for roughly no longer
158 /// than `ms` milliseconds. This method should not be used for
159 /// precise timing due to anomalies such as preemption or platform
160 /// differences that may not cause the maximum amount of time
161 /// waited to be precisely `ms`.
163 /// The returned boolean is `false` only if the timeout is known
166 /// Like `wait`, the lock specified will be re-acquired when this function
167 /// returns, regardless of whether the timeout elapsed or not.
168 #[stable(feature = "rust1", since = "1.0.0")]
169 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::sync::Condvar::wait_timeout`")]
170 pub fn wait_timeout_ms<'a, T>(&self, guard: MutexGuard<'a, T>, ms: u32)
171 -> LockResult<(MutexGuard<'a, T>, bool)> {
172 let res = self.wait_timeout(guard, Duration::from_millis(ms as u64));
173 poison::map_result(res, |(a, b)| {
178 /// Waits on this condition variable for a notification, timing out after a
179 /// specified duration.
181 /// The semantics of this function are equivalent to `wait()` except that
182 /// the thread will be blocked for roughly no longer than `dur`. This
183 /// method should not be used for precise timing due to anomalies such as
184 /// preemption or platform differences that may not cause the maximum
185 /// amount of time waited to be precisely `dur`.
187 /// The returned `WaitTimeoutResult` value indicates if the timeout is
188 /// known to have elapsed.
190 /// Like `wait`, the lock specified will be re-acquired when this function
191 /// returns, regardless of whether the timeout elapsed or not.
192 #[stable(feature = "wait_timeout", since = "1.5.0")]
193 pub fn wait_timeout<'a, T>(&self, guard: MutexGuard<'a, T>,
195 -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)> {
197 let me: &'static Condvar = &*(self as *const _);
198 me.inner.wait_timeout(guard, dur)
202 /// Wakes up one blocked thread on this condvar.
204 /// If there is a blocked thread on this condition variable, then it will
205 /// be woken up from its call to `wait` or `wait_timeout`. Calls to
206 /// `notify_one` are not buffered in any way.
208 /// To wake up all threads, see `notify_all()`.
209 #[stable(feature = "rust1", since = "1.0.0")]
210 pub fn notify_one(&self) { unsafe { self.inner.inner.notify_one() } }
212 /// Wakes up all blocked threads on this condvar.
214 /// This method will ensure that any current waiters on the condition
215 /// variable are awoken. Calls to `notify_all()` are not buffered in any
218 /// To wake up only one thread, see `notify_one()`.
219 #[stable(feature = "rust1", since = "1.0.0")]
220 pub fn notify_all(&self) { unsafe { self.inner.inner.notify_all() } }
223 #[stable(feature = "rust1", since = "1.0.0")]
224 impl Drop for Condvar {
226 unsafe { self.inner.inner.destroy() }
231 /// Creates a new condition variable
232 #[unstable(feature = "static_condvar",
233 reason = "may be merged with Condvar in the future",
235 pub const fn new() -> StaticCondvar {
237 inner: sys::Condvar::new(),
238 mutex: AtomicUsize::new(0),
242 /// Blocks the current thread until this condition variable receives a
245 /// See `Condvar::wait`.
246 #[unstable(feature = "static_condvar",
247 reason = "may be merged with Condvar in the future",
249 pub fn wait<'a, T>(&'static self, guard: MutexGuard<'a, T>)
250 -> LockResult<MutexGuard<'a, T>> {
251 let poisoned = unsafe {
252 let lock = mutex::guard_lock(&guard);
254 self.inner.wait(lock);
255 mutex::guard_poison(&guard).get()
258 Err(PoisonError::new(guard))
264 /// Waits on this condition variable for a notification, timing out after a
265 /// specified duration.
267 /// See `Condvar::wait_timeout`.
268 #[unstable(feature = "static_condvar",
269 reason = "may be merged with Condvar in the future",
271 pub fn wait_timeout<'a, T>(&'static self,
272 guard: MutexGuard<'a, T>,
274 -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)> {
275 let (poisoned, result) = unsafe {
276 let lock = mutex::guard_lock(&guard);
278 let success = self.inner.wait_timeout(lock, timeout);
279 (mutex::guard_poison(&guard).get(), WaitTimeoutResult(!success))
282 Err(PoisonError::new((guard, result)))
288 /// Waits on this condition variable for a notification, timing out after a
289 /// specified duration.
291 /// The implementation will repeatedly wait while the duration has not
292 /// passed and the function returns `false`.
294 /// See `Condvar::wait_timeout_with`.
295 #[unstable(feature = "static_condvar",
296 reason = "may be merged with Condvar in the future",
298 pub fn wait_timeout_with<'a, T, F>(&'static self,
299 guard: MutexGuard<'a, T>,
302 -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)>
303 where F: FnMut(LockResult<&mut T>) -> bool {
304 // This could be made more efficient by pushing the implementation into
306 let start = Instant::now();
307 let mut guard_result: LockResult<MutexGuard<'a, T>> = Ok(guard);
308 while !f(guard_result
311 .map_err(|e| PoisonError::new(&mut **e.get_mut()))) {
312 let consumed = start.elapsed();
313 let guard = guard_result.unwrap_or_else(|e| e.into_inner());
314 let (new_guard_result, timed_out) = if consumed > dur {
315 (Ok(guard), WaitTimeoutResult(true))
317 match self.wait_timeout(guard, dur - consumed) {
318 Ok((new_guard, timed_out)) => (Ok(new_guard), timed_out),
320 let (new_guard, no_timeout) = err.into_inner();
321 (Err(PoisonError::new(new_guard)), no_timeout)
325 guard_result = new_guard_result;
326 if timed_out.timed_out() {
327 let result = f(guard_result
330 .map_err(|e| PoisonError::new(&mut **e.get_mut())));
331 let result = WaitTimeoutResult(!result);
332 return poison::map_result(guard_result, |g| (g, result));
336 poison::map_result(guard_result, |g| (g, WaitTimeoutResult(false)))
339 /// Wakes up one blocked thread on this condvar.
341 /// See `Condvar::notify_one`.
342 #[unstable(feature = "static_condvar",
343 reason = "may be merged with Condvar in the future",
345 pub fn notify_one(&'static self) { unsafe { self.inner.notify_one() } }
347 /// Wakes up all blocked threads on this condvar.
349 /// See `Condvar::notify_all`.
350 #[unstable(feature = "static_condvar",
351 reason = "may be merged with Condvar in the future",
353 pub fn notify_all(&'static self) { unsafe { self.inner.notify_all() } }
355 /// Deallocates all resources associated with this static condvar.
357 /// This method is unsafe to call as there is no guarantee that there are no
358 /// active users of the condvar, and this also doesn't prevent any future
359 /// users of the condvar. This method is required to be called to not leak
360 /// memory on all platforms.
361 #[unstable(feature = "static_condvar",
362 reason = "may be merged with Condvar in the future",
364 pub unsafe fn destroy(&'static self) {
368 fn verify(&self, mutex: &sys_mutex::Mutex) {
369 let addr = mutex as *const _ as usize;
370 match self.mutex.compare_and_swap(0, addr, Ordering::SeqCst) {
371 // If we got out 0, then we have successfully bound the mutex to
375 // If we get out a value that's the same as `addr`, then someone
376 // already beat us to the punch.
379 // Anything else and we're using more than one mutex on this cvar,
380 // which is currently disallowed.
381 _ => panic!("attempted to use a condition variable with two \
391 use super::StaticCondvar;
392 use sync::mpsc::channel;
393 use sync::{StaticMutex, Condvar, Mutex, Arc};
394 use sync::atomic::{AtomicUsize, Ordering};
401 let c = Condvar::new();
408 static C: StaticCondvar = StaticCondvar::new();
411 unsafe { C.destroy(); }
416 static C: StaticCondvar = StaticCondvar::new();
417 static M: StaticMutex = StaticMutex::new();
419 let g = M.lock().unwrap();
420 let _t = thread::spawn(move|| {
421 let _g = M.lock().unwrap();
424 let g = C.wait(g).unwrap();
426 unsafe { C.destroy(); M.destroy(); }
433 let data = Arc::new((Mutex::new(0), Condvar::new()));
434 let (tx, rx) = channel();
436 let data = data.clone();
438 thread::spawn(move|| {
439 let &(ref lock, ref cond) = &*data;
440 let mut cnt = lock.lock().unwrap();
443 tx.send(()).unwrap();
446 cnt = cond.wait(cnt).unwrap();
448 tx.send(()).unwrap();
453 let &(ref lock, ref cond) = &*data;
455 let mut cnt = lock.lock().unwrap();
466 fn wait_timeout_ms() {
467 static C: StaticCondvar = StaticCondvar::new();
468 static M: StaticMutex = StaticMutex::new();
470 let g = M.lock().unwrap();
471 let (g, _no_timeout) = C.wait_timeout(g, Duration::from_millis(1)).unwrap();
472 // spurious wakeups mean this isn't necessarily true
473 // assert!(!no_timeout);
474 let _t = thread::spawn(move || {
475 let _g = M.lock().unwrap();
478 let (g, timeout_res) = C.wait_timeout(g, Duration::from_millis(u32::MAX as u64)).unwrap();
479 assert!(!timeout_res.timed_out());
481 unsafe { C.destroy(); M.destroy(); }
485 fn wait_timeout_with() {
486 static C: StaticCondvar = StaticCondvar::new();
487 static M: StaticMutex = StaticMutex::new();
488 static S: AtomicUsize = AtomicUsize::new(0);
490 let g = M.lock().unwrap();
491 let (g, timed_out) = C.wait_timeout_with(g, Duration::new(0, 1000), |_| {
494 assert!(timed_out.timed_out());
496 let (tx, rx) = channel();
497 let _t = thread::spawn(move || {
499 let g = M.lock().unwrap();
500 S.store(1, Ordering::SeqCst);
505 let g = M.lock().unwrap();
506 S.store(2, Ordering::SeqCst);
511 let _g = M.lock().unwrap();
512 S.store(3, Ordering::SeqCst);
517 let day = 24 * 60 * 60;
518 let (_g, timed_out) = C.wait_timeout_with(g, Duration::new(day, 0), |_| {
519 assert_eq!(state, S.load(Ordering::SeqCst));
520 tx.send(()).unwrap();
527 assert!(!timed_out.timed_out());
533 static M1: StaticMutex = StaticMutex::new();
534 static M2: StaticMutex = StaticMutex::new();
535 static C: StaticCondvar = StaticCondvar::new();
537 let mut g = M1.lock().unwrap();
538 let _t = thread::spawn(move|| {
539 let _g = M1.lock().unwrap();
542 g = C.wait(g).unwrap();
545 let _ = C.wait(M2.lock().unwrap()).unwrap();