Rust Barrier — rendezvous before a shared readout

Contents

Barrier is for when every worker must hit the same line before anyone moves on—useful if you want a shared readout after parallel work.

Say you’re doing parallel work and want every thread to finish before you read the final result. The usual approach is to join each handle:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
use std::sync::{Arc, Mutex};

fn main() {
let numthreads = 10;
let my_mutex = Arc::new(Mutex::new(0));
let mut handlers = Vec::with_capacity(numthreads);

for _ in 0..numthreads {
let my_lock = my_mutex.clone();
handlers.push(std::thread::spawn(move || {
let mut guard = my_lock.lock().unwrap();
*guard += 1;
}));
}
for handler in handlers {
handler.join().unwrap();
}

let answer = { *my_mutex.lock().unwrap() };
assert_eq!(answer, numthreads);
}

With a Barrier, you can structure it like this:

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
use std::sync::{Arc, Barrier, Mutex};

fn main() {
let numthreads = 10;
let my_mutex = Arc::new(Mutex::new(0));

// We use a barrier to ensure the readout happens after all writing
let barrier = Arc::new(Barrier::new(numthreads + 1));

for i in 0..numthreads {
let my_barrier = barrier.clone();
let my_lock = my_mutex.clone();
std::thread::spawn(move || {
let mut guard = my_lock.lock().unwrap();
*guard += 1;

// Release the lock to prevent a deadlock
drop(guard);
println!("thread {} is ready", i);
// Blocks the current thread until all threads have rendezvoused here.
my_barrier.wait();
println!("thread {} is done", i)
});
}

// A barrier will block `n`-1 threads which call [`wait()`] and then wake
// up all threads at once when the `n`th thread calls [`wait()`].
barrier.wait();

let answer = { *my_mutex.lock().unwrap() };
assert_eq!(answer, numthreads);
}

Barrier::wait coordinates n parties; you fix n when you create the barrier. Each wait blocks until the nth caller arrives, then everyone wakes and continues—like a gate every thread must reach before anyone moves on.

Compared with join-all, this version has real overhead when thread counts grow; internally it’s condvar plus mutex. That pairing is its own topic—see Rust Condvar.

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