Tokio Semaphore — alternating 1 and 2 with two threads
A semaphore caps how many concurrent actors can use a resource.
Unlike a mutex (exclusive access), a semaphore hands out a fixed number of permits. Think of a bucket of tokens: each visitor acquires a token; when the bucket is empty, new acquires block until someone adds permits or releases them.
Below we use the classic two-thread print puzzle to see how that feels in code.
There’s no stable std::sync::Semaphore (std::sync::Semaphore was deprecated in 1.7.0). Examples use tokio‘s semaphore.
Add tokio to your crate:
1 2 3 4 5
# Add tokio to cargo.toml by hand # Or with cargo-add: cargo add tokio --features sync,macros,rt-multi-thread [dependencies] tokio = { version = "1.34.0", features = ["sync", "macros", "rt-multi-thread"] }
Naive version: one permit
Start with a semaphore that allows one holder. Two tasks acquire, print, and drop the permit:
lett2 = tokio::spawn(asyncmove { for_in0..cnt { // Or use `_` to drop the permit immediately let_ = semaphore2.acquire().await.unwrap(); print!("2 "); } });
tokio::try_join!(t1, t2).unwrap(); }
Looks fine, but output isn’t guaranteed to be 1 2 1 2 1 2.
We only enforced “one permit at a time,” not who goes first. That’s mutual exclusion, not alternation.
Strict alternation: two semaphores
Drive ordering by moving permits between two semaphores—add_permits on one side, forget on the other so the permit doesn’t bounce back to the same bucket.
#[tokio::main] asyncfnmain() { // Bucket 1 starts with one permit so thread 1 can print first letsemaphore = Arc::new(Semaphore::new(1)); letcnt = 3; letsemaphore2 = semaphore.clone();
// Bucket 2 starts empty until thread 1 adds a permit letsemaphore_wait = Arc::new(Semaphore::new(0)); letsemaphore_wait2 = semaphore_wait.clone();
lett1 = tokio::spawn(asyncmove { for_in0..cnt { letpermit = semaphore.acquire().await.unwrap(); print!("1 "); // Consume permit — don't return it to bucket 1 permit.forget(); // Unblock bucket 2 so thread 2 can print semaphore_wait2.add_permits(1); } });
lett2 = tokio::spawn(asyncmove { for_in0..cnt { letpermit = semaphore_wait.acquire().await.unwrap(); print!("2 "); // Consume permit — don't return it to bucket 2 permit.forget(); // Unblock bucket 1 for the next 1 semaphore2.add_permits(1); } });
tokio::try_join!(t1, t2).unwrap(); }
Two dynamic permit buckets handshake the turns.
Compare with the condvar version to see how each primitive shapes the solution.