Use std::sync::Barrier to make multiple threads wait until they all reach a specific point before proceeding. Create a Barrier with the number of threads, clone it for each thread, and call .wait() to block until all threads arrive.
use std::sync::Barrier;
use std::thread;
fn main() {
let num_threads = 4;
let barrier = Arc::new(Barrier::new(num_threads));
let mut handles = vec![];
for _ in 0..num_threads {
let b = barrier.clone();
let handle = thread::spawn(move || {
println!("Thread waiting at barrier");
b.wait(); // Blocks until all threads arrive
println!("Thread passed barrier");
});
handles.push(handle);
}
for h in handles {
h.join().unwrap();
}
}
Note: Import Arc from std::sync to share the barrier across threads.