5 use crate::sync::{mutex, poison, LockResult, MutexGuard, PoisonError};
6 use crate::sys_common::condvar as sys;
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`]: Condvar::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 = Arc::clone(&pair);
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.
65 #[stable(feature = "wait_timeout", since = "1.5.0")]
66 pub fn timed_out(&self) -> bool {
71 /// A Condition Variable
73 /// Condition variables represent the ability to block a thread such that it
74 /// consumes no CPU time while waiting for an event to occur. Condition
75 /// variables are typically associated with a boolean predicate (a condition)
76 /// and a mutex. The predicate is always verified inside of the mutex before
77 /// determining that a thread must block.
79 /// Functions in this module will block the current **thread** of execution.
80 /// Note that any attempt to use multiple mutexes on the same condition
81 /// variable may result in a runtime panic.
86 /// use std::sync::{Arc, Mutex, Condvar};
89 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
90 /// let pair2 = Arc::clone(&pair);
92 /// // Inside of our lock, spawn a new thread, and then wait for it to start.
93 /// thread::spawn(move|| {
94 /// let (lock, cvar) = &*pair2;
95 /// let mut started = lock.lock().unwrap();
97 /// // We notify the condvar that the value has changed.
98 /// cvar.notify_one();
101 /// // Wait for the thread to start up.
102 /// let (lock, cvar) = &*pair;
103 /// let mut started = lock.lock().unwrap();
104 /// while !*started {
105 /// started = cvar.wait(started).unwrap();
108 #[stable(feature = "rust1", since = "1.0.0")]
114 /// Creates a new condition variable which is ready to be waited on and
120 /// use std::sync::Condvar;
122 /// let condvar = Condvar::new();
124 #[stable(feature = "rust1", since = "1.0.0")]
126 pub fn new() -> Condvar {
127 Condvar { inner: sys::Condvar::new() }
130 /// Blocks the current thread until this condition variable receives a
133 /// This function will atomically unlock the mutex specified (represented by
134 /// `guard`) and block the current thread. This means that any calls
135 /// to [`notify_one`] or [`notify_all`] which happen logically after the
136 /// mutex is unlocked are candidates to wake this thread up. When this
137 /// function call returns, the lock specified will have been re-acquired.
139 /// Note that this function is susceptible to spurious wakeups. Condition
140 /// variables normally have a boolean predicate associated with them, and
141 /// the predicate must always be checked each time this function returns to
142 /// protect against spurious wakeups.
146 /// This function will return an error if the mutex being waited on is
147 /// poisoned when this thread re-acquires the lock. For more information,
148 /// see information about [poisoning] on the [`Mutex`] type.
152 /// This function may [`panic!`] if it is used with more than one mutex
155 /// [`notify_one`]: Self::notify_one
156 /// [`notify_all`]: Self::notify_all
157 /// [poisoning]: super::Mutex#poisoning
158 /// [`Mutex`]: super::Mutex
163 /// use std::sync::{Arc, Mutex, Condvar};
166 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
167 /// let pair2 = Arc::clone(&pair);
169 /// thread::spawn(move|| {
170 /// let (lock, cvar) = &*pair2;
171 /// let mut started = lock.lock().unwrap();
173 /// // We notify the condvar that the value has changed.
174 /// cvar.notify_one();
177 /// // Wait for the thread to start up.
178 /// let (lock, cvar) = &*pair;
179 /// let mut started = lock.lock().unwrap();
180 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
181 /// while !*started {
182 /// started = cvar.wait(started).unwrap();
185 #[stable(feature = "rust1", since = "1.0.0")]
186 pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>) -> LockResult<MutexGuard<'a, T>> {
187 let poisoned = unsafe {
188 let lock = mutex::guard_lock(&guard);
189 self.inner.wait(lock);
190 mutex::guard_poison(&guard).get()
192 if poisoned { Err(PoisonError::new(guard)) } else { Ok(guard) }
195 /// Blocks the current thread until this condition variable receives a
196 /// notification and the provided condition is false.
198 /// This function will atomically unlock the mutex specified (represented by
199 /// `guard`) and block the current thread. This means that any calls
200 /// to [`notify_one`] or [`notify_all`] which happen logically after the
201 /// mutex is unlocked are candidates to wake this thread up. When this
202 /// function call returns, the lock specified will have been re-acquired.
206 /// This function will return an error if the mutex being waited on is
207 /// poisoned when this thread re-acquires the lock. For more information,
208 /// see information about [poisoning] on the [`Mutex`] type.
210 /// [`notify_one`]: Self::notify_one
211 /// [`notify_all`]: Self::notify_all
212 /// [poisoning]: super::Mutex#poisoning
213 /// [`Mutex`]: super::Mutex
218 /// use std::sync::{Arc, Mutex, Condvar};
221 /// let pair = Arc::new((Mutex::new(true), Condvar::new()));
222 /// let pair2 = Arc::clone(&pair);
224 /// thread::spawn(move|| {
225 /// let (lock, cvar) = &*pair2;
226 /// let mut pending = lock.lock().unwrap();
227 /// *pending = false;
228 /// // We notify the condvar that the value has changed.
229 /// cvar.notify_one();
232 /// // Wait for the thread to start up.
233 /// let (lock, cvar) = &*pair;
234 /// // As long as the value inside the `Mutex<bool>` is `true`, we wait.
235 /// let _guard = cvar.wait_while(lock.lock().unwrap(), |pending| { *pending }).unwrap();
237 #[stable(feature = "wait_until", since = "1.42.0")]
238 pub fn wait_while<'a, T, F>(
240 mut guard: MutexGuard<'a, T>,
242 ) -> LockResult<MutexGuard<'a, T>>
244 F: FnMut(&mut T) -> bool,
246 while condition(&mut *guard) {
247 guard = self.wait(guard)?;
252 /// Waits on this condition variable for a notification, timing out after a
253 /// specified duration.
255 /// The semantics of this function are equivalent to [`wait`]
256 /// except that the thread will be blocked for roughly no longer
257 /// than `ms` milliseconds. This method should not be used for
258 /// precise timing due to anomalies such as preemption or platform
259 /// differences that might not cause the maximum amount of time
260 /// waited to be precisely `ms`.
262 /// Note that the best effort is made to ensure that the time waited is
263 /// measured with a monotonic clock, and not affected by the changes made to
266 /// The returned boolean is `false` only if the timeout is known
269 /// Like [`wait`], the lock specified will be re-acquired when this function
270 /// returns, regardless of whether the timeout elapsed or not.
272 /// [`wait`]: Self::wait
277 /// use std::sync::{Arc, Mutex, Condvar};
280 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
281 /// let pair2 = Arc::clone(&pair);
283 /// thread::spawn(move|| {
284 /// let (lock, cvar) = &*pair2;
285 /// let mut started = lock.lock().unwrap();
287 /// // We notify the condvar that the value has changed.
288 /// cvar.notify_one();
291 /// // Wait for the thread to start up.
292 /// let (lock, cvar) = &*pair;
293 /// let mut started = lock.lock().unwrap();
294 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
296 /// let result = cvar.wait_timeout_ms(started, 10).unwrap();
297 /// // 10 milliseconds have passed, or maybe the value changed!
298 /// started = result.0;
299 /// if *started == true {
300 /// // We received the notification and the value has been updated, we can leave.
305 #[stable(feature = "rust1", since = "1.0.0")]
306 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::sync::Condvar::wait_timeout`")]
307 pub fn wait_timeout_ms<'a, T>(
309 guard: MutexGuard<'a, T>,
311 ) -> LockResult<(MutexGuard<'a, T>, bool)> {
312 let res = self.wait_timeout(guard, Duration::from_millis(ms as u64));
313 poison::map_result(res, |(a, b)| (a, !b.timed_out()))
316 /// Waits on this condition variable for a notification, timing out after a
317 /// specified duration.
319 /// The semantics of this function are equivalent to [`wait`] except that
320 /// the thread will be blocked for roughly no longer than `dur`. This
321 /// method should not be used for precise timing due to anomalies such as
322 /// preemption or platform differences that might not cause the maximum
323 /// amount of time waited to be precisely `dur`.
325 /// Note that the best effort is made to ensure that the time waited is
326 /// measured with a monotonic clock, and not affected by the changes made to
327 /// the system time. This function is susceptible to spurious wakeups.
328 /// Condition variables normally have a boolean predicate associated with
329 /// them, and the predicate must always be checked each time this function
330 /// returns to protect against spurious wakeups. Additionally, it is
331 /// typically desirable for the timeout to not exceed some duration in
332 /// spite of spurious wakes, thus the sleep-duration is decremented by the
333 /// amount slept. Alternatively, use the `wait_timeout_while` method
334 /// to wait with a timeout while a predicate is true.
336 /// The returned [`WaitTimeoutResult`] value indicates if the timeout is
337 /// known to have elapsed.
339 /// Like [`wait`], the lock specified will be re-acquired when this function
340 /// returns, regardless of whether the timeout elapsed or not.
342 /// [`wait`]: Self::wait
343 /// [`wait_timeout_while`]: Self::wait_timeout_while
348 /// use std::sync::{Arc, Mutex, Condvar};
350 /// use std::time::Duration;
352 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
353 /// let pair2 = Arc::clone(&pair);
355 /// thread::spawn(move|| {
356 /// let (lock, cvar) = &*pair2;
357 /// let mut started = lock.lock().unwrap();
359 /// // We notify the condvar that the value has changed.
360 /// cvar.notify_one();
363 /// // wait for the thread to start up
364 /// let (lock, cvar) = &*pair;
365 /// let mut started = lock.lock().unwrap();
366 /// // as long as the value inside the `Mutex<bool>` is `false`, we wait
368 /// let result = cvar.wait_timeout(started, Duration::from_millis(10)).unwrap();
369 /// // 10 milliseconds have passed, or maybe the value changed!
370 /// started = result.0;
371 /// if *started == true {
372 /// // We received the notification and the value has been updated, we can leave.
377 #[stable(feature = "wait_timeout", since = "1.5.0")]
378 pub fn wait_timeout<'a, T>(
380 guard: MutexGuard<'a, T>,
382 ) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)> {
383 let (poisoned, result) = unsafe {
384 let lock = mutex::guard_lock(&guard);
385 let success = self.inner.wait_timeout(lock, dur);
386 (mutex::guard_poison(&guard).get(), WaitTimeoutResult(!success))
388 if poisoned { Err(PoisonError::new((guard, result))) } else { Ok((guard, result)) }
391 /// Waits on this condition variable for a notification, timing out after a
392 /// specified duration.
394 /// The semantics of this function are equivalent to [`wait_while`] except
395 /// that the thread will be blocked for roughly no longer than `dur`. This
396 /// method should not be used for precise timing due to anomalies such as
397 /// preemption or platform differences that might not cause the maximum
398 /// amount of time waited to be precisely `dur`.
400 /// Note that the best effort is made to ensure that the time waited is
401 /// measured with a monotonic clock, and not affected by the changes made to
404 /// The returned [`WaitTimeoutResult`] value indicates if the timeout is
405 /// known to have elapsed without the condition being met.
407 /// Like [`wait_while`], the lock specified will be re-acquired when this
408 /// function returns, regardless of whether the timeout elapsed or not.
410 /// [`wait_while`]: Self::wait_while
411 /// [`wait_timeout`]: Self::wait_timeout
416 /// use std::sync::{Arc, Mutex, Condvar};
418 /// use std::time::Duration;
420 /// let pair = Arc::new((Mutex::new(true), Condvar::new()));
421 /// let pair2 = Arc::clone(&pair);
423 /// thread::spawn(move|| {
424 /// let (lock, cvar) = &*pair2;
425 /// let mut pending = lock.lock().unwrap();
426 /// *pending = false;
427 /// // We notify the condvar that the value has changed.
428 /// cvar.notify_one();
431 /// // wait for the thread to start up
432 /// let (lock, cvar) = &*pair;
433 /// let result = cvar.wait_timeout_while(
434 /// lock.lock().unwrap(),
435 /// Duration::from_millis(100),
436 /// |&mut pending| pending,
438 /// if result.1.timed_out() {
439 /// // timed-out without the condition ever evaluating to false.
441 /// // access the locked mutex via result.0
443 #[stable(feature = "wait_timeout_until", since = "1.42.0")]
444 pub fn wait_timeout_while<'a, T, F>(
446 mut guard: MutexGuard<'a, T>,
449 ) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)>
451 F: FnMut(&mut T) -> bool,
453 let start = Instant::now();
455 if !condition(&mut *guard) {
456 return Ok((guard, WaitTimeoutResult(false)));
458 let timeout = match dur.checked_sub(start.elapsed()) {
459 Some(timeout) => timeout,
460 None => return Ok((guard, WaitTimeoutResult(true))),
462 guard = self.wait_timeout(guard, timeout)?.0;
466 /// Wakes up one blocked thread on this condvar.
468 /// If there is a blocked thread on this condition variable, then it will
469 /// be woken up from its call to [`wait`] or [`wait_timeout`]. Calls to
470 /// `notify_one` are not buffered in any way.
472 /// To wake up all threads, see [`notify_all`].
474 /// [`wait`]: Self::wait
475 /// [`wait_timeout`]: Self::wait_timeout
476 /// [`notify_all`]: Self::notify_all
481 /// use std::sync::{Arc, Mutex, Condvar};
484 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
485 /// let pair2 = Arc::clone(&pair);
487 /// thread::spawn(move|| {
488 /// let (lock, cvar) = &*pair2;
489 /// let mut started = lock.lock().unwrap();
491 /// // We notify the condvar that the value has changed.
492 /// cvar.notify_one();
495 /// // Wait for the thread to start up.
496 /// let (lock, cvar) = &*pair;
497 /// let mut started = lock.lock().unwrap();
498 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
499 /// while !*started {
500 /// started = cvar.wait(started).unwrap();
503 #[stable(feature = "rust1", since = "1.0.0")]
504 pub fn notify_one(&self) {
505 self.inner.notify_one()
508 /// Wakes up all blocked threads on this condvar.
510 /// This method will ensure that any current waiters on the condition
511 /// variable are awoken. Calls to `notify_all()` are not buffered in any
514 /// To wake up only one thread, see [`notify_one`].
516 /// [`notify_one`]: Self::notify_one
521 /// use std::sync::{Arc, Mutex, Condvar};
524 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
525 /// let pair2 = Arc::clone(&pair);
527 /// thread::spawn(move|| {
528 /// let (lock, cvar) = &*pair2;
529 /// let mut started = lock.lock().unwrap();
531 /// // We notify the condvar that the value has changed.
532 /// cvar.notify_all();
535 /// // Wait for the thread to start up.
536 /// let (lock, cvar) = &*pair;
537 /// let mut started = lock.lock().unwrap();
538 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
539 /// while !*started {
540 /// started = cvar.wait(started).unwrap();
543 #[stable(feature = "rust1", since = "1.0.0")]
544 pub fn notify_all(&self) {
545 self.inner.notify_all()
549 #[stable(feature = "std_debug", since = "1.16.0")]
550 impl fmt::Debug for Condvar {
551 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
552 f.debug_struct("Condvar").finish_non_exhaustive()
556 #[stable(feature = "condvar_default", since = "1.10.0")]
557 impl Default for Condvar {
558 /// Creates a `Condvar` which is ready to be waited on and notified.
559 fn default() -> Condvar {