Barrier Syncs Thread Phases

Barrier::wait blocks until every thread in the group arrives, releasing them together each round so phase boundaries stay aligned across workers.

RustResilience

Code

rustsnippet
28 lines
use std::sync::{Arc, Barrier};
use std::thread;

fn main() {
    let workers = 3;
    let barrier = Arc::new(Barrier::new(workers));
    let mut handles = Vec::new();

    for id in 0..workers {
        let barrier = Arc::clone(&barrier);
        handles.push(thread::spawn(move || {
            for phase in 1..=2 {
                // 各自完成本阶段的活
                let work = (id + 1) * phase;
                println!("worker {id} finished {work}");
                // wait 阻塞直到 workers 个线程全部到齐,然后一起放行
                let leader = barrier.wait().is_leader();
                // 每轮恰好一个线程拿到 leader:适合做汇总打印
                if leader {
                    println!("phase {phase} complete for all {workers}");
                }
            }
        }));
    }
    for handle in handles {
        handle.join().unwrap();
    }
}

How the snippet works

Barrier Syncs Thread Phases reduces to the function main.

Iteration happens inside for id in 0..workers — everything outside it runs once.

Using it

The demo output is labeled (worker, phase), so every printed line maps back to its originating operation.

Key statements

handle.join().unwrap();

Interactive Tools for This Topic

FAQ

What does Barrier Syncs Thread Phases print when run?
Invoke the file as-is — the `worker`, `phase` prefixes identify which step printed each line.