I'm having unexpected results when playing around with Condvar
. I know that I can't trust that my wait()
won't wake up early, but in my case it seems that consistently one of my wake-ups is missing. Given this example code:
use std::sync::{Arc, Mutex, Condvar};
use std::{
thread,
time
};
fn main() {
let pair = Arc::new((Mutex::new(false), Condvar::new()));
let pause = time::Duration::from_secs(1);
for id in 0..10 {
let pair2 = pair.clone();
thread::spawn(move|| {
let &(ref lock, ref cvar) = &*pair2;
let lock = lock.lock().unwrap();
let _ = cvar.wait(lock).unwrap();
println!("Thread {} done!", id);
});
}
// Wait for the thread to start up.
let &(ref _lock, ref cvar) = &*pair;
for _ in 0..10 {
thread::sleep(pause);
cvar.notify_one();
}
}
I'm only getting the first eight threads out of the loop:
Thread 0 done!
Thread 1 done!
Thread 2 done!
Thread 3 done!
Thread 4 done!
Thread 5 done!
Thread 6 done!
Thread 7 done!
Thread 8 done!
If I increase the count on the second loop to 11, it does actually wake up all nine.
I've double checked the documentation on both wait()
and notify_one()
but it's not obvious what's wrong here.
Any thoughts? Is this a bug or something I'm just not doing right?