The Barrier post used condvar plus mutex under the hood; here the condvar is the main character.
A condition variable lets threads block in wait without spinning, until another thread notifys them.
Minimal example:
1 | use std::sync::{Arc, Condvar, Mutex}; |
A spawned thread flips started and wakes the waiter. Main blocks in wait until that happens.
wait takes the lock’s MutexGuard: it releases the mutex, parks the thread, and on wake re-acquires the lock and hands the guard back so you can read the protected state.
Tip:
MutexGuardreleases the lock on drop and derefs to the inner value.
Two details bite people in interviews:
- Why pair condvar with a mutex?
- Why re-check the condition after a wake?
It comes down to how wakes actually behave.
Wake order is not guaranteed
We spawn two batches of equal size: workers bump a counter and notify_one; waiters block on wait. This prints who woke when:
1 | use std::sync::{Arc, Condvar, Mutex}; |
Output varies. Five notifies might wake waiters out of worker order (workers still increment in a sensible order because they hold the lock):
1 | Woker thread 0 before notify: Counter 1 |
You can even get fewer wakes than waiters, so someone blocks forever:
1 | Woker thread 1 before notify: Counter 1 |
OS condition variables don’t promise FIFO wake order—scheduling picks among runnable waiters. Imposing order would cost extra for little gain when you only care that some waiter progresses. There’s a good thread on wake ordering.
So with many waiters on one cvar, notify_one isn’t a strict one-to-one with wait, and you can’t assume each wake hits a different thread.
A waiter can stall when notifies race ahead of waits: notify_one with nobody parked is a no-op, so you can end up with fewer wakes than waiters.
Spurious wakeups
A wait can return even when your predicate is false—sometimes without a matching notify. That’s spurious wakeup, not a Rust bug; it’s how the underlying primitives work.
Put together: always wait in a loop that re-checks the condition under the mutex so reads of shared state stay race-free.
Beyond wait, the std API also has notify_all, wait_while, and wait_timeout. The docs have solid examples; I won’t repeat them here.
For something closer to production, WaitGroup behaves like Barrier without fixing the thread count up front—crossbeam’s version is tight and worth a read: wait_group.rs.
More in this series: Rust posts.
Questions? Leave a comment below or email: newbvirgil@gmail.com![]()
