Rust Condvar — waits, notify, and rechecking the condition

Contents

  1. 1. Wake order is not guaranteed
  2. 2. Spurious wakeups

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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;
let mut started = lock.lock().unwrap();
*started = true;
// We notify the condvar that the value has changed.
cvar.notify_one();
});

// Wait for the thread to start up.
let (lock, cvar) = &*pair;
let mut started = lock.lock().unwrap();
while !*started {
started = cvar.wait(started).unwrap();
}
}

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: MutexGuard releases 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
use std::sync::{Arc, Condvar, Mutex};
use std::thread::{self};

struct SharedData {
counter: Mutex<usize>,
condvar: Condvar,
}

fn main() {
let shared_data = Arc::new(SharedData {
counter: Mutex::new(0),
condvar: Condvar::new(),
});
let thread_num = 5;
let mut workers = Vec::new();
let mut waits = Vec::new();

for i in 0..thread_num {
do_wait(i, Arc::clone(&shared_data), &mut waits);
}
for i in 0..thread_num {
do_work(i, Arc::clone(&shared_data), &mut workers)
}
waits.into_iter().for_each(|w| w.join().unwrap());
workers.into_iter().for_each(|w| w.join().unwrap());
}

fn do_work(i: i32, data: Arc<SharedData>, workers: &mut Vec<thread::JoinHandle<()>>) {
workers.push(thread::spawn(move || {
let SharedData { counter, condvar } = &*data;
let mut data = counter.lock().unwrap();
*data += 1;
println!("Woker thread {} before notify: Counter {}", i, data);
condvar.notify_one();
}));
}
fn do_wait(i: i32, data: Arc<SharedData>, waits: &mut Vec<thread::JoinHandle<()>>) {
waits.push(thread::spawn(move || {
let SharedData { counter, condvar } = &*data;
let mut data = counter.lock().unwrap();
data = condvar.wait(data).unwrap();
println!(" Wait thread {} after wake up: Counter {}", i, data);
}));
}

Output varies. Five notifies might wake waiters out of worker order (workers still increment in a sensible order because they hold the lock):

1
2
3
4
5
6
7
8
9
10
Woker thread 0 before notify: Counter 1
Woker thread 4 before notify: Counter 2
Woker thread 2 before notify: Counter 3
Wait thread 1 after wake up: Counter 3
Wait thread 3 after wake up: Counter 3
Woker thread 3 before notify: Counter 4
Wait thread 0 after wake up: Counter 4
Woker thread 1 before notify: Counter 5
Wait thread 4 after wake up: Counter 5
Wait thread 2 after wake up: Counter 5

You can even get fewer wakes than waiters, so someone blocks forever:

1
2
3
4
5
6
7
8
9
10
Woker thread 1 before notify: Counter 1
Wait thread 2 after wake up: Counter 1
Woker thread 3 before notify: Counter 2
Woker thread 0 before notify: Counter 3
Wait thread 4 after wake up: Counter 3
Woker thread 4 before notify: Counter 4
Wait thread 3 after wake up: Counter 4
Wait thread 1 after wake up: Counter 4
Woker thread 2 before notify: Counter 5
# one thread stuck here

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