RRust By Example
advancedConcurrency

Barrier Synchronization

Synchronize multiple threads with Barrier.

Barrier Synchronization

Synchronize multiple threads with Barrier.

Difficulty

Advanced

Code

rust
use std::sync::{Arc, Barrier};
use std::thread;

fn main() {
    let barrier = Arc::new(Barrier::new(3));
    let mut handles = vec![];

    for i in 0..3 {
        let barrier = Arc::clone(&barrier);
        handles.push(thread::spawn(move || {
            println!("thread {} before barrier", i);
            barrier.wait();
            println!("thread {} after barrier", i);
        }));
    }

    for h in handles {
        h.join().unwrap();
    }
}

Explanation

Barrier synchronizes N threads at a checkpoint.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the concurrency category to build a complete understanding of this topic.

More Concurrency Examples