Sub topic 14
Condvar: waiting for a condition
This chapter assumes you know Arc<Mutex<T>>, lock guards, and thread::spawn with move closures. It covers how one thread waits until another thread changes shared state, without spinning.
The problem: waiting without burning CPU
A Mutex protects data, but it does not tell you when the data changes. Suppose the main thread needs a worker to finish setup first. You could lock the mutex in a loop and check a flag. That busy-waits: the thread uses a full CPU core and does nothing useful.
A Condvar (condition variable) fixes this. A thread that must wait gives up the lock and sleeps. Another thread changes the state and wakes it up.
A Condvar is always paired with a Mutex. The mutex guards the condition, which is the data you are waiting on. The Condvar carries the notification.
A first example
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");
}The mutex and condvar sit in a tuple inside one Arc, so both threads share them together. The program prints ready.
How `wait` works
Instead, here is the sequence as a diagram.
The call cvar.wait(ready) does three things:
- It takes your
MutexGuardand releases the lock. - It puts the thread to sleep until another thread notifies the condvar.
- When woken, it reacquires the lock and returns a new guard.
Because wait consumes the guard and returns a new one, you must assign the result back: ready = cvar.wait(ready).unwrap();. The unwrap handles a poisoned mutex, as in the earlier poisoning chapter.
Always wait in a loop
The example uses while !*ready, not if. There are two reasons.
- Spurious wakeups. The operating system may wake a waiting thread without any notification. The loop checks the condition again and goes back to sleep if it is still false.
- Missed notifications. If the worker sets the flag and notifies before the main thread starts waiting, the notification is lost. Because the flag is stored under the lock, the main thread sees
trueon its first check and never waits.
The rule is: the condition lives in the mutex-protected data, and the loop tests it every time.
Condvar also has wait_while, which does the loop for you:
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 guard = cvar
.wait_while(lock.lock().unwrap(), |ready| !*ready)
.unwrap();
println!("ready: {}", *guard);
}The closure returns true while the thread should keep waiting.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Using `if` instead of `while` | Proceeds after a spurious wakeup with the condition false | Loop, or use `wait_while` |
| Using one condvar with two different mutexes | Panics or behaves unpredictably | Pair each condvar with exactly one mutex |
| Setting the flag without holding the lock | Race that can lose a wakeup | Change the state under the lock |
| Using `notify_one` when several threads wait for different things | The wrong thread may wake | Use `notify_all` and let each recheck |
Exercise
Why does cvar.wait(ready) take the MutexGuard by value and return a guard, and why must it be called inside a while loop?
Show answer
It takes the guard so it can release the lock while the thread sleeps, then returns a new guard after reacquiring the lock on wake-up. The loop is needed because wake-ups can be spurious, so the thread must recheck the condition each time and wait again if it is still false.
Exercise
A worker sets a flag and calls notify_one before the main thread reaches wait. Does the main thread hang forever?
Show answer
No. The flag is stored in the mutex-protected data, so the main thread sees it is already true when it checks the condition and never calls wait.