Sub topic 14
Condvar: waiting for a condition
A Mutex protects data, but it can't tell a thread when that data has changed. This chapter covers Condvar, the standard library's tool for sleeping until another thread changes shared state. It assumes you know Arc<Mutex<T>>, lock guards, thread::spawn with move closures, and Result handling with unwrap.
The problem: waiting without wasting CPU
Suppose a worker thread must finish setup before the main thread continues. With only a Mutex<bool>, the main thread has to poll:
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
fn main() {
let ready = Arc::new(Mutex::new(false));
let ready2 = Arc::clone(&ready);
thread::spawn(move || {
*ready2.lock().unwrap() = true;
});
// Busy-wait: correct, but burns CPU and adds latency.
loop {
if *ready.lock().unwrap() {
break;
}
thread::sleep(Duration::from_millis(10));
}
println!("ready");
}This works, but it forces a bad trade-off. A short sleep wastes CPU. A long sleep delays the reaction. A Condvar (condition variable) removes the trade-off. The waiting thread sleeps in the operating system and wakes when another thread notifies it.
The working model
A Condvar is always used together with a Mutex. Three parts make up the pattern:
- The mutex guards some state, such as a flag or a queue.
- The waiter locks the mutex, checks the state, and calls
waitif the state isn't what it needs. - The notifier changes the state under the same mutex, then calls
notify_oneornotify_all.
The key operation is wait. It takes your MutexGuard, releases the lock, and puts the thread to sleep. These two steps happen atomically, so no notification can slip in between them. When the thread wakes, wait re-acquires the lock and returns the guard to you. That is why the call looks like guard = cvar.wait(guard).unwrap().
The basic example
Here is the standard shape. The mutex and the condvar travel together in one tuple inside an Arc.
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
fn main() {
let pair = Arc::new((Mutex::new(false), Condvar::new()));
let pair2 = Arc::clone(&pair);
thread::spawn(move || {
let (lock, cvar) = &*pair2;
*lock.lock().unwrap() = true;
cvar.notify_one();
});
let (lock, cvar) = &*pair;
let mut ready = lock.lock().unwrap();
while !*ready {
ready = cvar.wait(ready).unwrap();
}
println!("ready");
}Points worth noting:
&*pair2dereferences theArcto the tuple, then borrows it. The patternlet (lock, cvar) = ...then splits the tuple into two references.- The worker's guard is a temporary. It drops at the end of the assignment statement, so the lock is already released when
notify_oneruns. - The waiter holds the lock while it checks
*ready. This prevents a race between "check the flag" and "go to sleep". waitreturns aLockResult, because a poisoned mutex makes it returnErr. Poisoning works the same way here as in the earlier chapter.
Why the `while` loop matters
Always put wait inside a loop that rechecks the condition. Two things can go wrong with a bare if.
Spurious wakeups. The operating system is allowed to wake a waiting thread even though nobody notified it. The documentation says so explicitly. Without a recheck, your code would continue with the condition still false.
Stolen conditions. With several consumers, another thread may get the lock first and consume the item you were woken for. When you finally get the lock, the condition is false again.
The state in the mutex is the truth. The notification is only a hint to look at it again.
A related error is the lost wakeup. If you notify before anyone is waiting, the notification is gone. A Condvar stores no memory of past notifications. This is why the flag exists. The waiter checks the flag first, so a notification that arrived early is still visible as state, and the waiter never sleeps.
`wait_while`: the loop built in
The loop is common enough that the standard library provides wait_while. It takes the guard and a closure that returns true while you should keep waiting. Here is a consumer waiting for items in a queue:
use std::collections::VecDeque;
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
fn main() {
let queue = Arc::new((Mutex::new(VecDeque::new()), Condvar::new()));
let producer = {
let queue = Arc::clone(&queue);
thread::spawn(move || {
let (lock, cvar) = &*queue;
for i in 1..=3 {
lock.lock().unwrap().push_back(i);
cvar.notify_one();
}
})
};
let (lock, cvar) = &*queue;
let mut received = Vec::new();
while received.len() < 3 {
let mut guard = cvar
.wait_while(lock.lock().unwrap(), |q| q.is_empty())
.unwrap();
received.push(guard.pop_front().unwrap());
}
producer.join().unwrap();
println!("{:?}", received);
}This prints [1, 2, 3]. If the producer is fast, the queue may already hold several items. The consumer then finds q.is_empty() false and never sleeps. If the producer is slow, the consumer sleeps until the next notify_one. Both cases are handled by the same code.
Timeouts
A waiter that might never be woken should use a timeout. wait_timeout_while combines a deadline with the condition check:
use std::sync::{Condvar, Mutex};
use std::time::Duration;
fn main() {
let lock = Mutex::new(false);
let cvar = Condvar::new();
let guard = lock.lock().unwrap();
let (guard, result) = cvar
.wait_timeout_while(guard, Duration::from_millis(100), |ready| !*ready)
.unwrap();
println!("flag = {}, timed out = {}", *guard, result.timed_out());
}No thread ever sets the flag, so after about 100 ms the program prints flag = false, timed out = true. Use result.timed_out() to tell "the condition became true" apart from "we gave up".
The methods at a glance
| Method | Purpose |
|---|---|
| `wait(guard)` | Sleep until notified. You must recheck the condition yourself. |
| `wait_while(guard, f)` | Sleep while `f` returns `true`. Rechecks for you. |
| `wait_timeout(guard, dur)` | Like `wait`, but gives up after `dur`. |
| `wait_timeout_while(guard, dur, f)` | Like `wait_while`, with a time limit. |
| `notify_one()` | Wake one waiting thread. |
| `notify_all()` | Wake every waiting thread. |
Use notify_one when any single waiter can handle the change, such as one new item in a queue. Use notify_all when the change affects every waiter, such as a "shutdown" flag. Waking too many threads costs performance only. Waking too few can leave a thread asleep forever.
Common errors
- Using different mutexes. All waiters and notifiers of one
Condvarmust use the sameMutex. Mixing mutexes can panic at runtime. - Changing state without the lock. If the notifier changes the state without holding the mutex, the waiter can check, miss the change, and go to sleep just before the notification. Always change the state under the lock.
- Holding a guard across a long computation after waking. The guard returned by
waitstill holds the lock. Take what you need out of the state, then drop the guard before doing slow work, as in the chapter on critical sections. - Ignoring the result. Calling
.unwrap()turns a poisoned mutex into a panic in the waiter. That is often right, but make it a decision.
When to prefer something else
A Condvar fits when threads wait on a condition about shared state: a flag, a counter reaching a threshold, or a custom data structure. If you only pass values from one thread to another, an mpsc channel already does the sleeping and waking for you, and with less room for mistakes. For a one-time "wait until this thread is finished" signal, JoinHandle::join is simpler.
Exercise
A waiter calls cvar.wait(guard) once inside an if !*ready { ... } instead of a while loop. Give two situations where it will continue even though *ready is still false.
Show answer
First, a spurious wakeup: the operating system may wake the thread without any notification, and an if does not recheck the flag. Second, with several waiters, another thread can acquire the lock first and reset or consume the condition before this thread re-acquires the lock. Using while !*ready (or wait_while) rechecks the condition after every wakeup and fixes both.
Exercise
A notifier sets the flag to true and calls notify_one before the waiter thread has even started. The waiter then locks the mutex and uses the correct while !*ready loop. Does the waiter hang? Why or why not?
Show answer
It does not hang. The Condvar forgets the notification, but the flag is stored in the mutex. The waiter locks the mutex, sees *ready == true, skips the wait call, and continues. This is why the condition must live in the mutex-protected state.