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:

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
use std::sync::Arc;
use tokio::sync::Semaphore;

#[tokio::main]
async fn main() {
let semaphore = Arc::new(Semaphore::new(1));
let cnt = 3;
let semaphore2 = semaphore.clone();

let t1 = tokio::spawn(async move {
for _ in 0..cnt {
let permit = semaphore.acquire().await.unwrap();
print!("1 ");
// Optional — permit returns on drop
drop(permit);
}
});

let t2 = tokio::spawn(async move {
for _ in 0..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.

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
use std::sync::Arc;
use tokio::sync::Semaphore;

#[tokio::main]
async fn main() {
// Bucket 1 starts with one permit so thread 1 can print first
let semaphore = Arc::new(Semaphore::new(1));
let cnt = 3;
let semaphore2 = semaphore.clone();

// Bucket 2 starts empty until thread 1 adds a permit
let semaphore_wait = Arc::new(Semaphore::new(0));
let semaphore_wait2 = semaphore_wait.clone();

let t1 = tokio::spawn(async move {
for _ in 0..cnt {
let permit = 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);
}
});

let t2 = tokio::spawn(async move {
for _ in 0..cnt {
let permit = 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.

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