std-method
Condvar::wait: recheck the predicate
A wake-up can occur without the desired state change. Use a loop that checks the condition under the reacquired lock. The state transition must use the same mutex. Expected stdout (not executed): finished Common mistake: Using an if instead of rechecking after wake-up.
Formal Syntax & Structure
rust syntaxrust
cv.wait(guard) -> LockResult<MutexGuard<'_, T>>Working Example
Example Snippetrust
fn main() { use std::sync::{Condvar, Mutex}; let ready = Mutex::new(false); let cv = Condvar::new(); std::thread::scope(|s| { s.spawn(|| { *ready.lock().unwrap() = true; cv.notify_one(); }); let mut g = ready.lock().unwrap(); while !*g { g = cv.wait(g).unwrap(); } }); println!("finished");}