Rust Reference ยท Standard Library Modules
Rust Condvar type
Reference for std::sync::Condvar: waiting for a condition with a Mutex, wait_while, wait_timeout, notify_one and notify_all, spurious wakeups and lost-wakeup mistakes.
A std::sync::Condvar (condition variable) lets a thread sleep until another thread says that something has changed, without burning CPU in a loop. It always works together with a Mutex: the mutex protects the shared state (a flag, a queue, a counter), and the condvar is the doorbell. A waiting thread atomically releases the mutex and goes to sleep; when it wakes up it takes the mutex again before wait returns.
A wake-up does not mean the condition is true. Threads can wake spuriously, and another thread may have changed the state again before you run. So you always re-check the condition in a loop, or use wait_while, which does that for you.
use std::sync::{Condvar, Mutex}; let pair = (Mutex::new(false), Condvar::new());
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
impl Condvar { pub const fn new() -> Condvar; pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>) -> LockResult<MutexGuard<'a, T>>; pub fn wait_while<'a, T, F>(&self, guard: MutexGuard<'a, T>, condition: F) -> LockResult<MutexGuard<'a, T>> where F: FnMut(&mut T) -> bool; pub fn wait_timeout<'a, T>(&self, guard: MutexGuard<'a, T>, dur: Duration) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)>; pub fn wait_timeout_while<'a, T, F>(&self, guard: MutexGuard<'a, T>, dur: Duration, condition: F) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)> where F: FnMut(&mut T) -> bool; pub fn notify_one(&self); pub fn notify_all(&self); }
| Name | Description |
|---|---|
guard |
The locked mutex. It is given up while sleeping and handed back on return. |
condition |
For wait_while: keep waiting as long as this returns true. It sees &mut T, so it may also update the state. |
dur |
The longest time to sleep. |
WaitTimeoutResult |
Call .timed_out() to find out whether the time ran out. |
Returns. The guard again, inside a LockResult (poisoned if another holder panicked). Timeout variants also return a WaitTimeoutResult.
Errors and panics. Using one Condvar with two different mutexes at the same time may panic. The error value is a PoisonError carrying the guard, like Mutex::lock.
Usage notes
- Always loop (or
wait_while). The patternwhile !ready { guard = cvar.wait(guard).unwrap(); }handles spurious wake-ups and stolen events. A barewaitfollowed by an assumption is a bug. - Change the state before notifying. Update the data under the lock, then call
notify_*. If the waiter checks the condition first and goes to sleep after your notification, it still sees the new state, because the check and the sleep happen atomically with the lock released. notify_onewakes one waiter,notify_allwakes all. With several different conditions on one condvar, usenotify_alland let each waiter re-check. A separateCondvarper condition is simpler.- Notifying with nobody waiting does nothing. Notifications are not remembered. This is why the state lives in the mutex, not in the condvar.
- You do not need to hold the lock to notify, but doing so is never wrong.
- Timeouts have platform-dependent granularity; measure elapsed time with
Instantrather than trusting the requested duration. - Alternatives. For passing data between threads, an
mpscchannel is usually simpler than a mutex, a queue and a condvar. For one-shot signals, a channel of()orthread::parkalso work.