Rust Condvar — alternating 1 and 2 with two threads

Contents

Interview favorite: two concurrent threads must print 1 and 2 in strict alternation.

Plenty of solutions exist. Here we try condvar, building on the Condvar post.

Idea: one shared flag in a mutex, with the condvar gating who may proceed.

  • Thread 1: print 1 only when the flag is false, set it true, notify_one so thread 2 can run; otherwise spin in a while loop (blocking path via wait logic in the loop).
  • Thread 2: while the flag is false, wait; when true, reset false and print 2.
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
45
46
47
use std::sync::{Arc, Condvar, Mutex};
use std::thread;

fn main() {
let pair = Arc::new((Mutex::new(false), Condvar::new()));
let cnt = 3;
let pair2 = pair.clone();

let t1 = thread::spawn(move || {
let &(ref lock, ref cvar) = &*pair2;
for _ in 0..cnt {
while let Ok(mut v) = lock.lock() {
// When flag is false, print 1, set true, wake the other thread
if !*v {
print!("1 ");
*v = true;
cvar.notify_one();
break;
} else {
// Drop the guard so we don't hold the mutex until scope end
// If there's nothing else to do, scope drop is fine too
drop(v);
// [2]
// std::thread::sleep(std::time::Duration::from_millis(1));
// [1]
// print!(" waitting... ");
}
}
}
});
let t2 = thread::spawn(move || {
for _ in 0..cnt {
let &(ref lock, ref cvar) = &*pair;
let mut v = lock.lock().unwrap();
// While false, wait until notified and flag becomes true
while !*v {
v = cvar.wait(v).unwrap();
}
// Reset and print 2
*v = false;

print!("2 ");
}
});
t1.join().unwrap();
t2.join().unwrap();
}

You should see 1 2 1 2 1 2 .

Thread 1’s busy loop still burns CPU. Uncomment the [1] debug print and you’ll see lots of waitting... lines.

A short sleep at [2] yields the core and cuts down lock thrashing.

The same puzzle with semaphores is fun too—that’s in Tokio Semaphore — alternating print.

Questions? Leave a comment below or email: newbvirgil@gmail.com