2 use crate::sync::atomic::{AtomicUsize, Ordering};
3 use crate::sync::{mutex, MutexGuard, PoisonError};
4 use crate::sys_common::condvar as sys;
5 use crate::sys_common::mutex as sys_mutex;
6 use crate::sys_common::poison::{self, LockResult};
7 use crate::time::{Duration, Instant};
9 /// A type indicating whether a timed wait on a condition variable returned
10 /// due to a time out or not.
12 /// It is returned by the [`wait_timeout`] method.
14 /// [`wait_timeout`]: struct.Condvar.html#method.wait_timeout
15 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
16 #[stable(feature = "wait_timeout", since = "1.5.0")]
17 pub struct WaitTimeoutResult(bool);
19 impl WaitTimeoutResult {
20 /// Returns `true` if the wait was known to have timed out.
24 /// This example spawns a thread which will update the boolean value and
25 /// then wait 100 milliseconds before notifying the condvar.
27 /// The main thread will wait with a timeout on the condvar and then leave
28 /// once the boolean has been updated and notified.
31 /// use std::sync::{Arc, Condvar, Mutex};
33 /// use std::time::Duration;
35 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
36 /// let pair2 = pair.clone();
38 /// thread::spawn(move || {
39 /// let (lock, cvar) = &*pair2;
41 /// // Let's wait 20 milliseconds before notifying the condvar.
42 /// thread::sleep(Duration::from_millis(20));
44 /// let mut started = lock.lock().unwrap();
45 /// // We update the boolean value.
47 /// cvar.notify_one();
50 /// // Wait for the thread to start up.
51 /// let (lock, cvar) = &*pair;
52 /// let mut started = lock.lock().unwrap();
54 /// // Let's put a timeout on the condvar's wait.
55 /// let result = cvar.wait_timeout(started, Duration::from_millis(10)).unwrap();
56 /// // 10 milliseconds have passed, or maybe the value changed!
57 /// started = result.0;
58 /// if *started == true {
59 /// // We received the notification and the value has been updated, we can leave.
64 #[stable(feature = "wait_timeout", since = "1.5.0")]
65 pub fn timed_out(&self) -> bool {
70 /// A Condition Variable
72 /// Condition variables represent the ability to block a thread such that it
73 /// consumes no CPU time while waiting for an event to occur. Condition
74 /// variables are typically associated with a boolean predicate (a condition)
75 /// and a mutex. The predicate is always verified inside of the mutex before
76 /// determining that a thread must block.
78 /// Functions in this module will block the current **thread** of execution and
79 /// are bindings to system-provided condition variables where possible. Note
80 /// that this module places one additional restriction over the system condition
81 /// variables: each condvar can be used with precisely one mutex at runtime. Any
82 /// attempt to use multiple mutexes on the same condition variable will result
83 /// in a runtime panic. If this is not desired, then the unsafe primitives in
84 /// `sys` do not have this restriction but may result in undefined behavior.
89 /// use std::sync::{Arc, Mutex, Condvar};
92 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
93 /// let pair2 = pair.clone();
95 /// // Inside of our lock, spawn a new thread, and then wait for it to start.
96 /// thread::spawn(move|| {
97 /// let (lock, cvar) = &*pair2;
98 /// let mut started = lock.lock().unwrap();
100 /// // We notify the condvar that the value has changed.
101 /// cvar.notify_one();
104 /// // Wait for the thread to start up.
105 /// let (lock, cvar) = &*pair;
106 /// let mut started = lock.lock().unwrap();
107 /// while !*started {
108 /// started = cvar.wait(started).unwrap();
111 #[stable(feature = "rust1", since = "1.0.0")]
113 inner: Box<sys::Condvar>,
118 /// Creates a new condition variable which is ready to be waited on and
124 /// use std::sync::Condvar;
126 /// let condvar = Condvar::new();
128 #[stable(feature = "rust1", since = "1.0.0")]
129 pub fn new() -> Condvar {
130 let mut c = Condvar { inner: box sys::Condvar::new(), mutex: AtomicUsize::new(0) };
137 /// Blocks the current thread until this condition variable receives a
140 /// This function will atomically unlock the mutex specified (represented by
141 /// `guard`) and block the current thread. This means that any calls
142 /// to [`notify_one`] or [`notify_all`] which happen logically after the
143 /// mutex is unlocked are candidates to wake this thread up. When this
144 /// function call returns, the lock specified will have been re-acquired.
146 /// Note that this function is susceptible to spurious wakeups. Condition
147 /// variables normally have a boolean predicate associated with them, and
148 /// the predicate must always be checked each time this function returns to
149 /// protect against spurious wakeups.
153 /// This function will return an error if the mutex being waited on is
154 /// poisoned when this thread re-acquires the lock. For more information,
155 /// see information about [poisoning] on the [`Mutex`] type.
159 /// This function will [`panic!`] if it is used with more than one mutex
160 /// over time. Each condition variable is dynamically bound to exactly one
161 /// mutex to ensure defined behavior across platforms. If this functionality
162 /// is not desired, then unsafe primitives in `sys` are provided.
164 /// [`notify_one`]: #method.notify_one
165 /// [`notify_all`]: #method.notify_all
166 /// [poisoning]: ../sync/struct.Mutex.html#poisoning
167 /// [`Mutex`]: ../sync/struct.Mutex.html
168 /// [`panic!`]: ../../std/macro.panic.html
173 /// use std::sync::{Arc, Mutex, Condvar};
176 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
177 /// let pair2 = pair.clone();
179 /// thread::spawn(move|| {
180 /// let (lock, cvar) = &*pair2;
181 /// let mut started = lock.lock().unwrap();
183 /// // We notify the condvar that the value has changed.
184 /// cvar.notify_one();
187 /// // Wait for the thread to start up.
188 /// let (lock, cvar) = &*pair;
189 /// let mut started = lock.lock().unwrap();
190 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
191 /// while !*started {
192 /// started = cvar.wait(started).unwrap();
195 #[stable(feature = "rust1", since = "1.0.0")]
196 pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>) -> LockResult<MutexGuard<'a, T>> {
197 let poisoned = unsafe {
198 let lock = mutex::guard_lock(&guard);
200 self.inner.wait(lock);
201 mutex::guard_poison(&guard).get()
203 if poisoned { Err(PoisonError::new(guard)) } else { Ok(guard) }
206 /// Blocks the current thread until this condition variable receives a
207 /// notification and the provided condition is false.
209 /// This function will atomically unlock the mutex specified (represented by
210 /// `guard`) and block the current thread. This means that any calls
211 /// to [`notify_one`] or [`notify_all`] which happen logically after the
212 /// mutex is unlocked are candidates to wake this thread up. When this
213 /// function call returns, the lock specified will have been re-acquired.
217 /// This function will return an error if the mutex being waited on is
218 /// poisoned when this thread re-acquires the lock. For more information,
219 /// see information about [poisoning] on the [`Mutex`] type.
221 /// [`notify_one`]: #method.notify_one
222 /// [`notify_all`]: #method.notify_all
223 /// [poisoning]: ../sync/struct.Mutex.html#poisoning
224 /// [`Mutex`]: ../sync/struct.Mutex.html
229 /// use std::sync::{Arc, Mutex, Condvar};
232 /// let pair = Arc::new((Mutex::new(true), Condvar::new()));
233 /// let pair2 = pair.clone();
235 /// thread::spawn(move|| {
236 /// let (lock, cvar) = &*pair2;
237 /// let mut pending = lock.lock().unwrap();
238 /// *pending = false;
239 /// // We notify the condvar that the value has changed.
240 /// cvar.notify_one();
243 /// // Wait for the thread to start up.
244 /// let (lock, cvar) = &*pair;
245 /// // As long as the value inside the `Mutex<bool>` is `true`, we wait.
246 /// let _guard = cvar.wait_while(lock.lock().unwrap(), |pending| { *pending }).unwrap();
248 #[stable(feature = "wait_until", since = "1.42.0")]
249 pub fn wait_while<'a, T, F>(
251 mut guard: MutexGuard<'a, T>,
253 ) -> LockResult<MutexGuard<'a, T>>
255 F: FnMut(&mut T) -> bool,
257 while condition(&mut *guard) {
258 guard = self.wait(guard)?;
263 /// Waits on this condition variable for a notification, timing out after a
264 /// specified duration.
266 /// The semantics of this function are equivalent to [`wait`]
267 /// except that the thread will be blocked for roughly no longer
268 /// than `ms` milliseconds. This method should not be used for
269 /// precise timing due to anomalies such as preemption or platform
270 /// differences that may not cause the maximum amount of time
271 /// waited to be precisely `ms`.
273 /// Note that the best effort is made to ensure that the time waited is
274 /// measured with a monotonic clock, and not affected by the changes made to
277 /// The returned boolean is `false` only if the timeout is known
280 /// Like [`wait`], the lock specified will be re-acquired when this function
281 /// returns, regardless of whether the timeout elapsed or not.
283 /// [`wait`]: #method.wait
288 /// use std::sync::{Arc, Mutex, Condvar};
291 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
292 /// let pair2 = pair.clone();
294 /// thread::spawn(move|| {
295 /// let (lock, cvar) = &*pair2;
296 /// let mut started = lock.lock().unwrap();
298 /// // We notify the condvar that the value has changed.
299 /// cvar.notify_one();
302 /// // Wait for the thread to start up.
303 /// let (lock, cvar) = &*pair;
304 /// let mut started = lock.lock().unwrap();
305 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
307 /// let result = cvar.wait_timeout_ms(started, 10).unwrap();
308 /// // 10 milliseconds have passed, or maybe the value changed!
309 /// started = result.0;
310 /// if *started == true {
311 /// // We received the notification and the value has been updated, we can leave.
316 #[stable(feature = "rust1", since = "1.0.0")]
317 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::sync::Condvar::wait_timeout`")]
318 pub fn wait_timeout_ms<'a, T>(
320 guard: MutexGuard<'a, T>,
322 ) -> LockResult<(MutexGuard<'a, T>, bool)> {
323 let res = self.wait_timeout(guard, Duration::from_millis(ms as u64));
324 poison::map_result(res, |(a, b)| (a, !b.timed_out()))
327 /// Waits on this condition variable for a notification, timing out after a
328 /// specified duration.
330 /// The semantics of this function are equivalent to [`wait`] except that
331 /// the thread will be blocked for roughly no longer than `dur`. This
332 /// method should not be used for precise timing due to anomalies such as
333 /// preemption or platform differences that may not cause the maximum
334 /// amount of time waited to be precisely `dur`.
336 /// Note that the best effort is made to ensure that the time waited is
337 /// measured with a monotonic clock, and not affected by the changes made to
338 /// the system time. This function is susceptible to spurious wakeups.
339 /// Condition variables normally have a boolean predicate associated with
340 /// them, and the predicate must always be checked each time this function
341 /// returns to protect against spurious wakeups. Additionally, it is
342 /// typically desirable for the timeout to not exceed some duration in
343 /// spite of spurious wakes, thus the sleep-duration is decremented by the
344 /// amount slept. Alternatively, use the `wait_timeout_while` method
345 /// to wait with a timeout while a predicate is true.
347 /// The returned [`WaitTimeoutResult`] value indicates if the timeout is
348 /// known to have elapsed.
350 /// Like [`wait`], the lock specified will be re-acquired when this function
351 /// returns, regardless of whether the timeout elapsed or not.
353 /// [`wait`]: #method.wait
354 /// [`wait_timeout_while`]: #method.wait_timeout_while
355 /// [`WaitTimeoutResult`]: struct.WaitTimeoutResult.html
360 /// use std::sync::{Arc, Mutex, Condvar};
362 /// use std::time::Duration;
364 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
365 /// let pair2 = pair.clone();
367 /// thread::spawn(move|| {
368 /// let (lock, cvar) = &*pair2;
369 /// let mut started = lock.lock().unwrap();
371 /// // We notify the condvar that the value has changed.
372 /// cvar.notify_one();
375 /// // wait for the thread to start up
376 /// let (lock, cvar) = &*pair;
377 /// let mut started = lock.lock().unwrap();
378 /// // as long as the value inside the `Mutex<bool>` is `false`, we wait
380 /// let result = cvar.wait_timeout(started, Duration::from_millis(10)).unwrap();
381 /// // 10 milliseconds have passed, or maybe the value changed!
382 /// started = result.0;
383 /// if *started == true {
384 /// // We received the notification and the value has been updated, we can leave.
389 #[stable(feature = "wait_timeout", since = "1.5.0")]
390 pub fn wait_timeout<'a, T>(
392 guard: MutexGuard<'a, T>,
394 ) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)> {
395 let (poisoned, result) = unsafe {
396 let lock = mutex::guard_lock(&guard);
398 let success = self.inner.wait_timeout(lock, dur);
399 (mutex::guard_poison(&guard).get(), WaitTimeoutResult(!success))
401 if poisoned { Err(PoisonError::new((guard, result))) } else { Ok((guard, result)) }
404 /// Waits on this condition variable for a notification, timing out after a
405 /// specified duration.
407 /// The semantics of this function are equivalent to [`wait_while`] except
408 /// that the thread will be blocked for roughly no longer than `dur`. This
409 /// method should not be used for precise timing due to anomalies such as
410 /// preemption or platform differences that may not cause the maximum
411 /// amount of time waited to be precisely `dur`.
413 /// Note that the best effort is made to ensure that the time waited is
414 /// measured with a monotonic clock, and not affected by the changes made to
417 /// The returned [`WaitTimeoutResult`] value indicates if the timeout is
418 /// known to have elapsed without the condition being met.
420 /// Like [`wait_while`], the lock specified will be re-acquired when this
421 /// function returns, regardless of whether the timeout elapsed or not.
423 /// [`wait_while`]: #method.wait_while
424 /// [`wait_timeout`]: #method.wait_timeout
425 /// [`WaitTimeoutResult`]: struct.WaitTimeoutResult.html
430 /// use std::sync::{Arc, Mutex, Condvar};
432 /// use std::time::Duration;
434 /// let pair = Arc::new((Mutex::new(true), Condvar::new()));
435 /// let pair2 = pair.clone();
437 /// thread::spawn(move|| {
438 /// let (lock, cvar) = &*pair2;
439 /// let mut pending = lock.lock().unwrap();
440 /// *pending = false;
441 /// // We notify the condvar that the value has changed.
442 /// cvar.notify_one();
445 /// // wait for the thread to start up
446 /// let (lock, cvar) = &*pair;
447 /// let result = cvar.wait_timeout_while(
448 /// lock.lock().unwrap(),
449 /// Duration::from_millis(100),
450 /// |&mut pending| pending,
452 /// if result.1.timed_out() {
453 /// // timed-out without the condition ever evaluating to false.
455 /// // access the locked mutex via result.0
457 #[stable(feature = "wait_timeout_until", since = "1.42.0")]
458 pub fn wait_timeout_while<'a, T, F>(
460 mut guard: MutexGuard<'a, T>,
463 ) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)>
465 F: FnMut(&mut T) -> bool,
467 let start = Instant::now();
469 if !condition(&mut *guard) {
470 return Ok((guard, WaitTimeoutResult(false)));
472 let timeout = match dur.checked_sub(start.elapsed()) {
473 Some(timeout) => timeout,
474 None => return Ok((guard, WaitTimeoutResult(true))),
476 guard = self.wait_timeout(guard, timeout)?.0;
480 /// Wakes up one blocked thread on this condvar.
482 /// If there is a blocked thread on this condition variable, then it will
483 /// be woken up from its call to [`wait`] or [`wait_timeout`]. Calls to
484 /// `notify_one` are not buffered in any way.
486 /// To wake up all threads, see [`notify_all`].
488 /// [`wait`]: #method.wait
489 /// [`wait_timeout`]: #method.wait_timeout
490 /// [`notify_all`]: #method.notify_all
495 /// use std::sync::{Arc, Mutex, Condvar};
498 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
499 /// let pair2 = pair.clone();
501 /// thread::spawn(move|| {
502 /// let (lock, cvar) = &*pair2;
503 /// let mut started = lock.lock().unwrap();
505 /// // We notify the condvar that the value has changed.
506 /// cvar.notify_one();
509 /// // Wait for the thread to start up.
510 /// let (lock, cvar) = &*pair;
511 /// let mut started = lock.lock().unwrap();
512 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
513 /// while !*started {
514 /// started = cvar.wait(started).unwrap();
517 #[stable(feature = "rust1", since = "1.0.0")]
518 pub fn notify_one(&self) {
519 unsafe { self.inner.notify_one() }
522 /// Wakes up all blocked threads on this condvar.
524 /// This method will ensure that any current waiters on the condition
525 /// variable are awoken. Calls to `notify_all()` are not buffered in any
528 /// To wake up only one thread, see [`notify_one`].
530 /// [`notify_one`]: #method.notify_one
535 /// use std::sync::{Arc, Mutex, Condvar};
538 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
539 /// let pair2 = pair.clone();
541 /// thread::spawn(move|| {
542 /// let (lock, cvar) = &*pair2;
543 /// let mut started = lock.lock().unwrap();
545 /// // We notify the condvar that the value has changed.
546 /// cvar.notify_all();
549 /// // Wait for the thread to start up.
550 /// let (lock, cvar) = &*pair;
551 /// let mut started = lock.lock().unwrap();
552 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
553 /// while !*started {
554 /// started = cvar.wait(started).unwrap();
557 #[stable(feature = "rust1", since = "1.0.0")]
558 pub fn notify_all(&self) {
559 unsafe { self.inner.notify_all() }
562 fn verify(&self, mutex: &sys_mutex::Mutex) {
563 let addr = mutex as *const _ as usize;
564 match self.mutex.compare_and_swap(0, addr, Ordering::SeqCst) {
565 // If we got out 0, then we have successfully bound the mutex to
569 // If we get out a value that's the same as `addr`, then someone
570 // already beat us to the punch.
573 // Anything else and we're using more than one mutex on this cvar,
574 // which is currently disallowed.
576 "attempted to use a condition variable with two \
583 #[stable(feature = "std_debug", since = "1.16.0")]
584 impl fmt::Debug for Condvar {
585 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
586 f.pad("Condvar { .. }")
590 #[stable(feature = "condvar_default", since = "1.10.0")]
591 impl Default for Condvar {
592 /// Creates a `Condvar` which is ready to be waited on and notified.
593 fn default() -> Condvar {
598 #[stable(feature = "rust1", since = "1.0.0")]
599 impl Drop for Condvar {
601 unsafe { self.inner.destroy() }
607 use crate::sync::atomic::{AtomicBool, Ordering};
608 use crate::sync::mpsc::channel;
609 use crate::sync::{Arc, Condvar, Mutex};
611 use crate::time::Duration;
615 let c = Condvar::new();
621 #[cfg_attr(target_os = "emscripten", ignore)]
623 let m = Arc::new(Mutex::new(()));
625 let c = Arc::new(Condvar::new());
628 let g = m.lock().unwrap();
629 let _t = thread::spawn(move || {
630 let _g = m2.lock().unwrap();
633 let g = c.wait(g).unwrap();
638 #[cfg_attr(target_os = "emscripten", ignore)]
642 let data = Arc::new((Mutex::new(0), Condvar::new()));
643 let (tx, rx) = channel();
645 let data = data.clone();
647 thread::spawn(move || {
648 let &(ref lock, ref cond) = &*data;
649 let mut cnt = lock.lock().unwrap();
652 tx.send(()).unwrap();
655 cnt = cond.wait(cnt).unwrap();
657 tx.send(()).unwrap();
662 let &(ref lock, ref cond) = &*data;
664 let mut cnt = lock.lock().unwrap();
675 #[cfg_attr(target_os = "emscripten", ignore)]
677 let pair = Arc::new((Mutex::new(false), Condvar::new()));
678 let pair2 = pair.clone();
680 // Inside of our lock, spawn a new thread, and then wait for it to start.
681 thread::spawn(move || {
682 let &(ref lock, ref cvar) = &*pair2;
683 let mut started = lock.lock().unwrap();
685 // We notify the condvar that the value has changed.
689 // Wait for the thread to start up.
690 let &(ref lock, ref cvar) = &*pair;
691 let guard = cvar.wait_while(lock.lock().unwrap(), |started| !*started);
692 assert!(*guard.unwrap());
696 #[cfg_attr(target_os = "emscripten", ignore)]
697 fn wait_timeout_wait() {
698 let m = Arc::new(Mutex::new(()));
699 let c = Arc::new(Condvar::new());
702 let g = m.lock().unwrap();
703 let (_g, no_timeout) = c.wait_timeout(g, Duration::from_millis(1)).unwrap();
704 // spurious wakeups mean this isn't necessarily true
705 // so execute test again, if not timeout
706 if !no_timeout.timed_out() {
715 #[cfg_attr(target_os = "emscripten", ignore)]
716 fn wait_timeout_while_wait() {
717 let m = Arc::new(Mutex::new(()));
718 let c = Arc::new(Condvar::new());
720 let g = m.lock().unwrap();
721 let (_g, wait) = c.wait_timeout_while(g, Duration::from_millis(1), |_| true).unwrap();
722 // no spurious wakeups. ensure it timed-out
723 assert!(wait.timed_out());
727 #[cfg_attr(target_os = "emscripten", ignore)]
728 fn wait_timeout_while_instant_satisfy() {
729 let m = Arc::new(Mutex::new(()));
730 let c = Arc::new(Condvar::new());
732 let g = m.lock().unwrap();
733 let (_g, wait) = c.wait_timeout_while(g, Duration::from_millis(0), |_| false).unwrap();
734 // ensure it didn't time-out even if we were not given any time.
735 assert!(!wait.timed_out());
739 #[cfg_attr(target_os = "emscripten", ignore)]
740 fn wait_timeout_while_wake() {
741 let pair = Arc::new((Mutex::new(false), Condvar::new()));
742 let pair_copy = pair.clone();
744 let &(ref m, ref c) = &*pair;
745 let g = m.lock().unwrap();
746 let _t = thread::spawn(move || {
747 let &(ref lock, ref cvar) = &*pair_copy;
748 let mut started = lock.lock().unwrap();
749 thread::sleep(Duration::from_millis(1));
754 .wait_timeout_while(g, Duration::from_millis(u64::MAX), |&mut notified| !notified)
756 // ensure it didn't time-out even if we were not given any time.
757 assert!(!wait.timed_out());
762 #[cfg_attr(target_os = "emscripten", ignore)]
763 fn wait_timeout_wake() {
764 let m = Arc::new(Mutex::new(()));
765 let c = Arc::new(Condvar::new());
768 let g = m.lock().unwrap();
773 let notified = Arc::new(AtomicBool::new(false));
774 let notified_copy = notified.clone();
776 let t = thread::spawn(move || {
777 let _g = m2.lock().unwrap();
778 thread::sleep(Duration::from_millis(1));
779 notified_copy.store(true, Ordering::SeqCst);
782 let (g, timeout_res) = c.wait_timeout(g, Duration::from_millis(u64::MAX)).unwrap();
783 assert!(!timeout_res.timed_out());
784 // spurious wakeups mean this isn't necessarily true
785 // so execute test again, if not notified
786 if !notified.load(Ordering::SeqCst) {
800 #[cfg_attr(target_os = "emscripten", ignore)]
802 let m = Arc::new(Mutex::new(()));
804 let c = Arc::new(Condvar::new());
807 let mut g = m.lock().unwrap();
808 let _t = thread::spawn(move || {
809 let _g = m2.lock().unwrap();
812 g = c.wait(g).unwrap();
815 let m = Mutex::new(());
816 let _ = c.wait(m.lock().unwrap()).unwrap();