5 use crate::sync::atomic::{AtomicUsize, Ordering};
6 use crate::sync::{mutex, MutexGuard, PoisonError};
7 use crate::sys_common::condvar as sys;
8 use crate::sys_common::mutex as sys_mutex;
9 use crate::sys_common::poison::{self, LockResult};
10 use crate::time::{Duration, Instant};
12 /// A type indicating whether a timed wait on a condition variable returned
13 /// due to a time out or not.
15 /// It is returned by the [`wait_timeout`] method.
17 /// [`wait_timeout`]: Condvar::wait_timeout
18 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
19 #[stable(feature = "wait_timeout", since = "1.5.0")]
20 pub struct WaitTimeoutResult(bool);
22 impl WaitTimeoutResult {
23 /// Returns `true` if the wait was known to have timed out.
27 /// This example spawns a thread which will update the boolean value and
28 /// then wait 100 milliseconds before notifying the condvar.
30 /// The main thread will wait with a timeout on the condvar and then leave
31 /// once the boolean has been updated and notified.
34 /// use std::sync::{Arc, Condvar, Mutex};
36 /// use std::time::Duration;
38 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
39 /// let pair2 = Arc::clone(&pair);
41 /// thread::spawn(move || {
42 /// let (lock, cvar) = &*pair2;
44 /// // Let's wait 20 milliseconds before notifying the condvar.
45 /// thread::sleep(Duration::from_millis(20));
47 /// let mut started = lock.lock().unwrap();
48 /// // We update the boolean value.
50 /// cvar.notify_one();
53 /// // Wait for the thread to start up.
54 /// let (lock, cvar) = &*pair;
55 /// let mut started = lock.lock().unwrap();
57 /// // Let's put a timeout on the condvar's wait.
58 /// let result = cvar.wait_timeout(started, Duration::from_millis(10)).unwrap();
59 /// // 10 milliseconds have passed, or maybe the value changed!
60 /// started = result.0;
61 /// if *started == true {
62 /// // We received the notification and the value has been updated, we can leave.
67 #[stable(feature = "wait_timeout", since = "1.5.0")]
68 pub fn timed_out(&self) -> bool {
73 /// A Condition Variable
75 /// Condition variables represent the ability to block a thread such that it
76 /// consumes no CPU time while waiting for an event to occur. Condition
77 /// variables are typically associated with a boolean predicate (a condition)
78 /// and a mutex. The predicate is always verified inside of the mutex before
79 /// determining that a thread must block.
81 /// Functions in this module will block the current **thread** of execution and
82 /// are bindings to system-provided condition variables where possible. Note
83 /// that this module places one additional restriction over the system condition
84 /// variables: each condvar can be used with precisely one mutex at runtime. Any
85 /// attempt to use multiple mutexes on the same condition variable will result
86 /// in a runtime panic. If this is not desired, then the unsafe primitives in
87 /// `sys` do not have this restriction but may result in undefined behavior.
92 /// use std::sync::{Arc, Mutex, Condvar};
95 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
96 /// let pair2 = Arc::clone(&pair);
98 /// // Inside of our lock, spawn a new thread, and then wait for it to start.
99 /// thread::spawn(move|| {
100 /// let (lock, cvar) = &*pair2;
101 /// let mut started = lock.lock().unwrap();
103 /// // We notify the condvar that the value has changed.
104 /// cvar.notify_one();
107 /// // Wait for the thread to start up.
108 /// let (lock, cvar) = &*pair;
109 /// let mut started = lock.lock().unwrap();
110 /// while !*started {
111 /// started = cvar.wait(started).unwrap();
114 #[stable(feature = "rust1", since = "1.0.0")]
116 inner: Box<sys::Condvar>,
121 /// Creates a new condition variable which is ready to be waited on and
127 /// use std::sync::Condvar;
129 /// let condvar = Condvar::new();
131 #[stable(feature = "rust1", since = "1.0.0")]
132 pub fn new() -> Condvar {
133 let mut c = Condvar { inner: box sys::Condvar::new(), mutex: AtomicUsize::new(0) };
140 /// Blocks the current thread until this condition variable receives a
143 /// This function will atomically unlock the mutex specified (represented by
144 /// `guard`) and block the current thread. This means that any calls
145 /// to [`notify_one`] or [`notify_all`] which happen logically after the
146 /// mutex is unlocked are candidates to wake this thread up. When this
147 /// function call returns, the lock specified will have been re-acquired.
149 /// Note that this function is susceptible to spurious wakeups. Condition
150 /// variables normally have a boolean predicate associated with them, and
151 /// the predicate must always be checked each time this function returns to
152 /// protect against spurious wakeups.
156 /// This function will return an error if the mutex being waited on is
157 /// poisoned when this thread re-acquires the lock. For more information,
158 /// see information about [poisoning] on the [`Mutex`] type.
162 /// This function will [`panic!`] if it is used with more than one mutex
163 /// over time. Each condition variable is dynamically bound to exactly one
164 /// mutex to ensure defined behavior across platforms. If this functionality
165 /// is not desired, then unsafe primitives in `sys` are provided.
167 /// [`notify_one`]: Self::notify_one
168 /// [`notify_all`]: Self::notify_all
169 /// [poisoning]: super::Mutex#poisoning
170 /// [`Mutex`]: super::Mutex
175 /// use std::sync::{Arc, Mutex, Condvar};
178 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
179 /// let pair2 = Arc::clone(&pair);
181 /// thread::spawn(move|| {
182 /// let (lock, cvar) = &*pair2;
183 /// let mut started = lock.lock().unwrap();
185 /// // We notify the condvar that the value has changed.
186 /// cvar.notify_one();
189 /// // Wait for the thread to start up.
190 /// let (lock, cvar) = &*pair;
191 /// let mut started = lock.lock().unwrap();
192 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
193 /// while !*started {
194 /// started = cvar.wait(started).unwrap();
197 #[stable(feature = "rust1", since = "1.0.0")]
198 pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>) -> LockResult<MutexGuard<'a, T>> {
199 let poisoned = unsafe {
200 let lock = mutex::guard_lock(&guard);
202 self.inner.wait(lock);
203 mutex::guard_poison(&guard).get()
205 if poisoned { Err(PoisonError::new(guard)) } else { Ok(guard) }
208 /// Blocks the current thread until this condition variable receives a
209 /// notification and the provided condition is false.
211 /// This function will atomically unlock the mutex specified (represented by
212 /// `guard`) and block the current thread. This means that any calls
213 /// to [`notify_one`] or [`notify_all`] which happen logically after the
214 /// mutex is unlocked are candidates to wake this thread up. When this
215 /// function call returns, the lock specified will have been re-acquired.
219 /// This function will return an error if the mutex being waited on is
220 /// poisoned when this thread re-acquires the lock. For more information,
221 /// see information about [poisoning] on the [`Mutex`] type.
223 /// [`notify_one`]: Self::notify_one
224 /// [`notify_all`]: Self::notify_all
225 /// [poisoning]: super::Mutex#poisoning
226 /// [`Mutex`]: super::Mutex
231 /// use std::sync::{Arc, Mutex, Condvar};
234 /// let pair = Arc::new((Mutex::new(true), Condvar::new()));
235 /// let pair2 = Arc::clone(&pair);
237 /// thread::spawn(move|| {
238 /// let (lock, cvar) = &*pair2;
239 /// let mut pending = lock.lock().unwrap();
240 /// *pending = false;
241 /// // We notify the condvar that the value has changed.
242 /// cvar.notify_one();
245 /// // Wait for the thread to start up.
246 /// let (lock, cvar) = &*pair;
247 /// // As long as the value inside the `Mutex<bool>` is `true`, we wait.
248 /// let _guard = cvar.wait_while(lock.lock().unwrap(), |pending| { *pending }).unwrap();
250 #[stable(feature = "wait_until", since = "1.42.0")]
251 pub fn wait_while<'a, T, F>(
253 mut guard: MutexGuard<'a, T>,
255 ) -> LockResult<MutexGuard<'a, T>>
257 F: FnMut(&mut T) -> bool,
259 while condition(&mut *guard) {
260 guard = self.wait(guard)?;
265 /// Waits on this condition variable for a notification, timing out after a
266 /// specified duration.
268 /// The semantics of this function are equivalent to [`wait`]
269 /// except that the thread will be blocked for roughly no longer
270 /// than `ms` milliseconds. This method should not be used for
271 /// precise timing due to anomalies such as preemption or platform
272 /// differences that may not cause the maximum amount of time
273 /// waited to be precisely `ms`.
275 /// Note that the best effort is made to ensure that the time waited is
276 /// measured with a monotonic clock, and not affected by the changes made to
279 /// The returned boolean is `false` only if the timeout is known
282 /// Like [`wait`], the lock specified will be re-acquired when this function
283 /// returns, regardless of whether the timeout elapsed or not.
285 /// [`wait`]: Self::wait
290 /// use std::sync::{Arc, Mutex, Condvar};
293 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
294 /// let pair2 = Arc::clone(&pair);
296 /// thread::spawn(move|| {
297 /// let (lock, cvar) = &*pair2;
298 /// let mut started = lock.lock().unwrap();
300 /// // We notify the condvar that the value has changed.
301 /// cvar.notify_one();
304 /// // Wait for the thread to start up.
305 /// let (lock, cvar) = &*pair;
306 /// let mut started = lock.lock().unwrap();
307 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
309 /// let result = cvar.wait_timeout_ms(started, 10).unwrap();
310 /// // 10 milliseconds have passed, or maybe the value changed!
311 /// started = result.0;
312 /// if *started == true {
313 /// // We received the notification and the value has been updated, we can leave.
318 #[stable(feature = "rust1", since = "1.0.0")]
319 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::sync::Condvar::wait_timeout`")]
320 pub fn wait_timeout_ms<'a, T>(
322 guard: MutexGuard<'a, T>,
324 ) -> LockResult<(MutexGuard<'a, T>, bool)> {
325 let res = self.wait_timeout(guard, Duration::from_millis(ms as u64));
326 poison::map_result(res, |(a, b)| (a, !b.timed_out()))
329 /// Waits on this condition variable for a notification, timing out after a
330 /// specified duration.
332 /// The semantics of this function are equivalent to [`wait`] except that
333 /// the thread will be blocked for roughly no longer than `dur`. This
334 /// method should not be used for precise timing due to anomalies such as
335 /// preemption or platform differences that may not cause the maximum
336 /// amount of time waited to be precisely `dur`.
338 /// Note that the best effort is made to ensure that the time waited is
339 /// measured with a monotonic clock, and not affected by the changes made to
340 /// the system time. This function is susceptible to spurious wakeups.
341 /// Condition variables normally have a boolean predicate associated with
342 /// them, and the predicate must always be checked each time this function
343 /// returns to protect against spurious wakeups. Additionally, it is
344 /// typically desirable for the timeout to not exceed some duration in
345 /// spite of spurious wakes, thus the sleep-duration is decremented by the
346 /// amount slept. Alternatively, use the `wait_timeout_while` method
347 /// to wait with a timeout while a predicate is true.
349 /// The returned [`WaitTimeoutResult`] value indicates if the timeout is
350 /// known to have elapsed.
352 /// Like [`wait`], the lock specified will be re-acquired when this function
353 /// returns, regardless of whether the timeout elapsed or not.
355 /// [`wait`]: Self::wait
356 /// [`wait_timeout_while`]: Self::wait_timeout_while
361 /// use std::sync::{Arc, Mutex, Condvar};
363 /// use std::time::Duration;
365 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
366 /// let pair2 = Arc::clone(&pair);
368 /// thread::spawn(move|| {
369 /// let (lock, cvar) = &*pair2;
370 /// let mut started = lock.lock().unwrap();
372 /// // We notify the condvar that the value has changed.
373 /// cvar.notify_one();
376 /// // wait for the thread to start up
377 /// let (lock, cvar) = &*pair;
378 /// let mut started = lock.lock().unwrap();
379 /// // as long as the value inside the `Mutex<bool>` is `false`, we wait
381 /// let result = cvar.wait_timeout(started, Duration::from_millis(10)).unwrap();
382 /// // 10 milliseconds have passed, or maybe the value changed!
383 /// started = result.0;
384 /// if *started == true {
385 /// // We received the notification and the value has been updated, we can leave.
390 #[stable(feature = "wait_timeout", since = "1.5.0")]
391 pub fn wait_timeout<'a, T>(
393 guard: MutexGuard<'a, T>,
395 ) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)> {
396 let (poisoned, result) = unsafe {
397 let lock = mutex::guard_lock(&guard);
399 let success = self.inner.wait_timeout(lock, dur);
400 (mutex::guard_poison(&guard).get(), WaitTimeoutResult(!success))
402 if poisoned { Err(PoisonError::new((guard, result))) } else { Ok((guard, result)) }
405 /// Waits on this condition variable for a notification, timing out after a
406 /// specified duration.
408 /// The semantics of this function are equivalent to [`wait_while`] except
409 /// that the thread will be blocked for roughly no longer than `dur`. This
410 /// method should not be used for precise timing due to anomalies such as
411 /// preemption or platform differences that may not cause the maximum
412 /// amount of time waited to be precisely `dur`.
414 /// Note that the best effort is made to ensure that the time waited is
415 /// measured with a monotonic clock, and not affected by the changes made to
418 /// The returned [`WaitTimeoutResult`] value indicates if the timeout is
419 /// known to have elapsed without the condition being met.
421 /// Like [`wait_while`], the lock specified will be re-acquired when this
422 /// function returns, regardless of whether the timeout elapsed or not.
424 /// [`wait_while`]: Self::wait_while
425 /// [`wait_timeout`]: Self::wait_timeout
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 = Arc::clone(&pair);
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`]: Self::wait
489 /// [`wait_timeout`]: Self::wait_timeout
490 /// [`notify_all`]: Self::notify_all
495 /// use std::sync::{Arc, Mutex, Condvar};
498 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
499 /// let pair2 = Arc::clone(&pair);
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`]: Self::notify_one
535 /// use std::sync::{Arc, Mutex, Condvar};
538 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
539 /// let pair2 = Arc::clone(&pair);
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() }