Rust `std::sync::Barrier;` erroneous with lots of threads

Hi, I was struggling with weird behaviour when using lots of Threads and a Barrier.

According to the documentation example 2, this sample should create a Barrier and all threads must wait to rendez vous there prior to executing : thus leading to a no interleaved stdout. But it does not work if you set the amount of created threads to 512 for instance :

This demonstrates a faulty behaviour of std::sync::Barrier :

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

let mut handles = Vec::with_capacity(10);
let barrier = Arc::new(Barrier::new(10));
for _ in 0..512 { // <- here, put 512 threads instead of 10
    let c = barrier.clone();
    // The same messages will be printed together.
    // You will NOT see any interleaving.
    handles.push(thread::spawn(move|| {
        println!("before wait");
        c.wait();
        println!("after wait");
    }));
}
// Wait for other threads to finish.
for handle in handles {
    handle.join().unwrap();
}

This sample from the doc seems to run fine :

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

let mut handles = Vec::with_capacity(10);
let barrier = Arc::new(Barrier::new(10));
for _ in 0..10 {
    let c = barrier.clone();
    // The same messages will be printed together.
    // You will NOT see any interleaving.
    handles.push(thread::spawn(move|| {
        println!("before wait");
        c.wait();
        println!("after wait");
    }));
}
// Wait for other threads to finish.
for handle in handles {
    handle.join().unwrap();
}

Alright, I totally misread the documentation : the Barrier must be initialised with the correct number of Threads it is supposed to block (and based on this count can it unlock once every thread is at rendez vous).

let barrier = Arc::new(Barrier::new(512)); // <- create a Barrier for handling lots of threads.
1 Like

No worries - everything you post here is one less thing I bump into myself :slight_smile: