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
1only when the flag is false, set it true,notify_oneso thread 2 can run; otherwise spin in awhileloop (blocking path via wait logic in the loop). - Thread 2: while the flag is false,
wait; when true, reset false and print2.
1 | use std::sync::{Arc, Condvar, Mutex}; |
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![]()
