Barrier Blocks Threads Until All Arrive
Hold three threads at a Barrier until all arrive, then confirm exactly one thread per phase receives the leader signal.
Code
use std::sync::{Arc, Barrier};
use std::thread;
fn main() {
// Barrier::wait holds the threads until all 3 have arrived
let barrier = Arc::new(Barrier::new(3));
let mut handles = Vec::new();
for id in 1..=3u32 {
let barrier = Arc::clone(&barrier);
handles.push(thread::spawn(move || {
let result = barrier.wait();
(id, result.wait())
}));
}
// collect and sort so thread scheduling order never decides the output
let mut results: Vec<(u32, bool)> = handles.into_iter().map(|h| h.join().unwrap()).collect();
results.sort();
let leaders = results.iter().filter(|(_, leader)| *leader).count();
println!("exactly one leader per phase: {}", leaders == 1);
for (id, _) in results {
println!("worker {id} passed the barrier");
}
}How the snippet works
Barrier Blocks Threads Until All Arrive is built around the function main.
Repetition is confined to for id in 1..=3u32 — the rest of the file is straight-line.
Using it
The demo output is labeled (exactly one leader per phase:, worker); each label names the call that printed it.
Key statements
let mut results: Vec<(u32, bool)> = handles.into_iter().map(|h| h.join().unwrap()).collect();
let leaders = results.iter().filter(|(_, leader)| *leader).count();
handles.push(thread::spawn(move || {
let result = barrier.wait();
(id, result.wait())
}));
Interactive Tools for This Topic
FAQ
- What does Barrier Blocks Threads Until All Arrive print when run?
- The script runs standalone; its 2 labeled outputs include `exactly one leader per phase:`, `worker`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.