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();
}