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.
12 use sync::atomic::{AtomicUsize, Ordering};
13 use sync::{mutex, MutexGuard, PoisonError};
14 use sys_common::condvar as sys;
15 use sys_common::mutex as sys_mutex;
16 use sys_common::poison::{self, LockResult};
19 /// A type indicating whether a timed wait on a condition variable returned
20 /// due to a time out or not.
22 /// It is returned by the [`wait_timeout`] method.
24 /// [`wait_timeout`]: struct.Condvar.html#method.wait_timeout
25 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
26 #[stable(feature = "wait_timeout", since = "1.5.0")]
27 pub struct WaitTimeoutResult(bool);
29 impl WaitTimeoutResult {
30 /// Returns whether the wait was known to have timed out.
34 /// This example spawns a thread which will update the boolean value and
35 /// then wait 100 milliseconds before notifying the condvar.
37 /// The main thread will wait with a timeout on the condvar and then leave
38 /// once the boolean has been updated and notified.
41 /// use std::sync::{Arc, Mutex, Condvar};
43 /// use std::time::Duration;
45 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
46 /// let pair2 = pair.clone();
48 /// thread::spawn(move|| {
49 /// let &(ref lock, ref cvar) = &*pair2;
50 /// let mut started = lock.lock().unwrap();
51 /// // We update the boolean value.
53 /// // Let's wait 20 milliseconds before notifying the condvar.
54 /// thread::sleep(Duration::from_millis(20));
55 /// cvar.notify_one();
58 /// // Wait for the thread to start up.
59 /// let &(ref lock, ref cvar) = &*pair;
60 /// let mut started = lock.lock().unwrap();
62 /// // Let's put a timeout on the condvar's wait.
63 /// let result = cvar.wait_timeout(started, Duration::from_millis(10)).unwrap();
64 /// // 10 milliseconds have passed, or maybe the value changed!
65 /// started = result.0;
66 /// if *started == true {
67 /// // We received the notification and the value has been updated, we can leave.
72 #[stable(feature = "wait_timeout", since = "1.5.0")]
73 pub fn timed_out(&self) -> bool {
78 /// A Condition Variable
80 /// Condition variables represent the ability to block a thread such that it
81 /// consumes no CPU time while waiting for an event to occur. Condition
82 /// variables are typically associated with a boolean predicate (a condition)
83 /// and a mutex. The predicate is always verified inside of the mutex before
84 /// determining that a thread must block.
86 /// Functions in this module will block the current **thread** of execution and
87 /// are bindings to system-provided condition variables where possible. Note
88 /// that this module places one additional restriction over the system condition
89 /// variables: each condvar can be used with precisely one mutex at runtime. Any
90 /// attempt to use multiple mutexes on the same condition variable will result
91 /// in a runtime panic. If this is not desired, then the unsafe primitives in
92 /// `sys` do not have this restriction but may result in undefined behavior.
97 /// use std::sync::{Arc, Mutex, Condvar};
100 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
101 /// let pair2 = pair.clone();
103 /// // Inside of our lock, spawn a new thread, and then wait for it to start.
104 /// thread::spawn(move|| {
105 /// let &(ref lock, ref cvar) = &*pair2;
106 /// let mut started = lock.lock().unwrap();
108 /// // We notify the condvar that the value has changed.
109 /// cvar.notify_one();
112 /// // Wait for the thread to start up.
113 /// let &(ref lock, ref cvar) = &*pair;
114 /// let mut started = lock.lock().unwrap();
115 /// while !*started {
116 /// started = cvar.wait(started).unwrap();
119 #[stable(feature = "rust1", since = "1.0.0")]
121 inner: Box<sys::Condvar>,
126 /// Creates a new condition variable which is ready to be waited on and
132 /// use std::sync::Condvar;
134 /// let condvar = Condvar::new();
136 #[stable(feature = "rust1", since = "1.0.0")]
137 pub fn new() -> Condvar {
138 let mut c = Condvar {
139 inner: box sys::Condvar::new(),
140 mutex: AtomicUsize::new(0),
148 /// Blocks the current thread until this condition variable receives a
151 /// This function will atomically unlock the mutex specified (represented by
152 /// `guard`) and block the current thread. This means that any calls
153 /// to [`notify_one`] or [`notify_all`] which happen logically after the
154 /// mutex is unlocked are candidates to wake this thread up. When this
155 /// function call returns, the lock specified will have been re-acquired.
157 /// Note that this function is susceptible to spurious wakeups. Condition
158 /// variables normally have a boolean predicate associated with them, and
159 /// the predicate must always be checked each time this function returns to
160 /// protect against spurious wakeups.
164 /// This function will return an error if the mutex being waited on is
165 /// poisoned when this thread re-acquires the lock. For more information,
166 /// see information about [poisoning] on the [`Mutex`] type.
170 /// This function will [`panic!`] if it is used with more than one mutex
171 /// over time. Each condition variable is dynamically bound to exactly one
172 /// mutex to ensure defined behavior across platforms. If this functionality
173 /// is not desired, then unsafe primitives in `sys` are provided.
175 /// [`notify_one`]: #method.notify_one
176 /// [`notify_all`]: #method.notify_all
177 /// [poisoning]: ../sync/struct.Mutex.html#poisoning
178 /// [`Mutex`]: ../sync/struct.Mutex.html
179 /// [`panic!`]: ../../std/macro.panic.html
184 /// use std::sync::{Arc, Mutex, Condvar};
187 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
188 /// let pair2 = pair.clone();
190 /// thread::spawn(move|| {
191 /// let &(ref lock, ref cvar) = &*pair2;
192 /// let mut started = lock.lock().unwrap();
194 /// // We notify the condvar that the value has changed.
195 /// cvar.notify_one();
198 /// // Wait for the thread to start up.
199 /// let &(ref lock, ref cvar) = &*pair;
200 /// let mut started = lock.lock().unwrap();
201 /// // As long as the value inside the `Mutex` is false, we wait.
202 /// while !*started {
203 /// started = cvar.wait(started).unwrap();
206 #[stable(feature = "rust1", since = "1.0.0")]
207 pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>)
208 -> LockResult<MutexGuard<'a, T>> {
209 let poisoned = unsafe {
210 let lock = mutex::guard_lock(&guard);
212 self.inner.wait(lock);
213 mutex::guard_poison(&guard).get()
216 Err(PoisonError::new(guard))
222 /// Waits on this condition variable for a notification, timing out after a
223 /// specified duration.
225 /// The semantics of this function are equivalent to [`wait`]
226 /// except that the thread will be blocked for roughly no longer
227 /// than `ms` milliseconds. This method should not be used for
228 /// precise timing due to anomalies such as preemption or platform
229 /// differences that may not cause the maximum amount of time
230 /// waited to be precisely `ms`.
232 /// Note that the best effort is made to ensure that the time waited is
233 /// measured with a monotonic clock, and not affected by the changes made to
236 /// The returned boolean is `false` only if the timeout is known
239 /// Like [`wait`], the lock specified will be re-acquired when this function
240 /// returns, regardless of whether the timeout elapsed or not.
242 /// [`wait`]: #method.wait
247 /// use std::sync::{Arc, Mutex, Condvar};
250 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
251 /// let pair2 = pair.clone();
253 /// thread::spawn(move|| {
254 /// let &(ref lock, ref cvar) = &*pair2;
255 /// let mut started = lock.lock().unwrap();
257 /// // We notify the condvar that the value has changed.
258 /// cvar.notify_one();
261 /// // Wait for the thread to start up.
262 /// let &(ref lock, ref cvar) = &*pair;
263 /// let mut started = lock.lock().unwrap();
264 /// // As long as the value inside the `Mutex` is false, we wait.
266 /// let result = cvar.wait_timeout_ms(started, 10).unwrap();
267 /// // 10 milliseconds have passed, or maybe the value changed!
268 /// started = result.0;
269 /// if *started == true {
270 /// // We received the notification and the value has been updated, we can leave.
275 #[stable(feature = "rust1", since = "1.0.0")]
276 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::sync::Condvar::wait_timeout`")]
277 pub fn wait_timeout_ms<'a, T>(&self, guard: MutexGuard<'a, T>, ms: u32)
278 -> LockResult<(MutexGuard<'a, T>, bool)> {
279 let res = self.wait_timeout(guard, Duration::from_millis(ms as u64));
280 poison::map_result(res, |(a, b)| {
285 /// Waits on this condition variable for a notification, timing out after a
286 /// specified duration.
288 /// The semantics of this function are equivalent to [`wait`] except that
289 /// the thread will be blocked for roughly no longer than `dur`. This
290 /// method should not be used for precise timing due to anomalies such as
291 /// preemption or platform differences that may not cause the maximum
292 /// amount of time waited to be precisely `dur`.
294 /// Note that the best effort is made to ensure that the time waited is
295 /// measured with a monotonic clock, and not affected by the changes made to
298 /// The returned [`WaitTimeoutResult`] value indicates if the timeout is
299 /// known to have elapsed.
301 /// Like [`wait`], the lock specified will be re-acquired when this function
302 /// returns, regardless of whether the timeout elapsed or not.
304 /// [`wait`]: #method.wait
305 /// [`WaitTimeoutResult`]: struct.WaitTimeoutResult.html
310 /// use std::sync::{Arc, Mutex, Condvar};
312 /// use std::time::Duration;
314 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
315 /// let pair2 = pair.clone();
317 /// thread::spawn(move|| {
318 /// let &(ref lock, ref cvar) = &*pair2;
319 /// let mut started = lock.lock().unwrap();
321 /// // We notify the condvar that the value has changed.
322 /// cvar.notify_one();
325 /// // wait for the thread to start up
326 /// let &(ref lock, ref cvar) = &*pair;
327 /// let mut started = lock.lock().unwrap();
328 /// // as long as the value inside the `Mutex` is false, we wait
330 /// let result = cvar.wait_timeout(started, Duration::from_millis(10)).unwrap();
331 /// // 10 milliseconds have passed, or maybe the value changed!
332 /// started = result.0;
333 /// if *started == true {
334 /// // We received the notification and the value has been updated, we can leave.
339 #[stable(feature = "wait_timeout", since = "1.5.0")]
340 pub fn wait_timeout<'a, T>(&self, guard: MutexGuard<'a, T>,
342 -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)> {
343 let (poisoned, result) = unsafe {
344 let lock = mutex::guard_lock(&guard);
346 let success = self.inner.wait_timeout(lock, dur);
347 (mutex::guard_poison(&guard).get(), WaitTimeoutResult(!success))
350 Err(PoisonError::new((guard, result)))
356 /// Wakes up one blocked thread on this condvar.
358 /// If there is a blocked thread on this condition variable, then it will
359 /// be woken up from its call to [`wait`] or [`wait_timeout`]. Calls to
360 /// `notify_one` are not buffered in any way.
362 /// To wake up all threads, see [`notify_all`].
364 /// [`wait`]: #method.wait
365 /// [`wait_timeout`]: #method.wait_timeout
366 /// [`notify_all`]: #method.notify_all
371 /// use std::sync::{Arc, Mutex, Condvar};
374 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
375 /// let pair2 = pair.clone();
377 /// thread::spawn(move|| {
378 /// let &(ref lock, ref cvar) = &*pair2;
379 /// let mut started = lock.lock().unwrap();
381 /// // We notify the condvar that the value has changed.
382 /// cvar.notify_one();
385 /// // Wait for the thread to start up.
386 /// let &(ref lock, ref cvar) = &*pair;
387 /// let mut started = lock.lock().unwrap();
388 /// // As long as the value inside the `Mutex` is false, we wait.
389 /// while !*started {
390 /// started = cvar.wait(started).unwrap();
393 #[stable(feature = "rust1", since = "1.0.0")]
394 pub fn notify_one(&self) {
395 unsafe { self.inner.notify_one() }
398 /// Wakes up all blocked threads on this condvar.
400 /// This method will ensure that any current waiters on the condition
401 /// variable are awoken. Calls to `notify_all()` are not buffered in any
404 /// To wake up only one thread, see [`notify_one`].
406 /// [`notify_one`]: #method.notify_one
411 /// use std::sync::{Arc, Mutex, Condvar};
414 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
415 /// let pair2 = pair.clone();
417 /// thread::spawn(move|| {
418 /// let &(ref lock, ref cvar) = &*pair2;
419 /// let mut started = lock.lock().unwrap();
421 /// // We notify the condvar that the value has changed.
422 /// cvar.notify_all();
425 /// // Wait for the thread to start up.
426 /// let &(ref lock, ref cvar) = &*pair;
427 /// let mut started = lock.lock().unwrap();
428 /// // As long as the value inside the `Mutex` is false, we wait.
429 /// while !*started {
430 /// started = cvar.wait(started).unwrap();
433 #[stable(feature = "rust1", since = "1.0.0")]
434 pub fn notify_all(&self) {
435 unsafe { self.inner.notify_all() }
438 fn verify(&self, mutex: &sys_mutex::Mutex) {
439 let addr = mutex as *const _ as usize;
440 match self.mutex.compare_and_swap(0, addr, Ordering::SeqCst) {
441 // If we got out 0, then we have successfully bound the mutex to
445 // If we get out a value that's the same as `addr`, then someone
446 // already beat us to the punch.
449 // Anything else and we're using more than one mutex on this cvar,
450 // which is currently disallowed.
451 _ => panic!("attempted to use a condition variable with two \
457 #[stable(feature = "std_debug", since = "1.16.0")]
458 impl fmt::Debug for Condvar {
459 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
460 f.pad("Condvar { .. }")
464 #[stable(feature = "condvar_default", since = "1.10.0")]
465 impl Default for Condvar {
466 /// Creates a `Condvar` which is ready to be waited on and notified.
467 fn default() -> Condvar {
472 #[stable(feature = "rust1", since = "1.0.0")]
473 impl Drop for Condvar {
475 unsafe { self.inner.destroy() }
481 use sync::mpsc::channel;
482 use sync::{Condvar, Mutex, Arc};
489 let c = Condvar::new();
495 #[cfg_attr(target_os = "emscripten", ignore)]
497 let m = Arc::new(Mutex::new(()));
499 let c = Arc::new(Condvar::new());
502 let g = m.lock().unwrap();
503 let _t = thread::spawn(move|| {
504 let _g = m2.lock().unwrap();
507 let g = c.wait(g).unwrap();
512 #[cfg_attr(target_os = "emscripten", ignore)]
516 let data = Arc::new((Mutex::new(0), Condvar::new()));
517 let (tx, rx) = channel();
519 let data = data.clone();
521 thread::spawn(move|| {
522 let &(ref lock, ref cond) = &*data;
523 let mut cnt = lock.lock().unwrap();
526 tx.send(()).unwrap();
529 cnt = cond.wait(cnt).unwrap();
531 tx.send(()).unwrap();
536 let &(ref lock, ref cond) = &*data;
538 let mut cnt = lock.lock().unwrap();
549 #[cfg_attr(target_os = "emscripten", ignore)]
550 fn wait_timeout_ms() {
551 let m = Arc::new(Mutex::new(()));
553 let c = Arc::new(Condvar::new());
556 let g = m.lock().unwrap();
557 let (g, _no_timeout) = c.wait_timeout(g, Duration::from_millis(1)).unwrap();
558 // spurious wakeups mean this isn't necessarily true
559 // assert!(!no_timeout);
560 let _t = thread::spawn(move || {
561 let _g = m2.lock().unwrap();
564 let (g, timeout_res) = c.wait_timeout(g, Duration::from_millis(u32::MAX as u64)).unwrap();
565 assert!(!timeout_res.timed_out());
571 #[cfg_attr(target_os = "emscripten", ignore)]
573 let m = Arc::new(Mutex::new(()));
575 let c = Arc::new(Condvar::new());
578 let mut g = m.lock().unwrap();
579 let _t = thread::spawn(move|| {
580 let _g = m2.lock().unwrap();
583 g = c.wait(g).unwrap();
586 let m = Mutex::new(());
587 let _ = c.wait(m.lock().unwrap()).unwrap();