std-type

Condvar: wait for a protected condition

A condition variable coordinates waiting for a change in mutex-protected state. Waiting releases the mutex and later reacquires it. The predicate, not the notification itself, defines readiness. Expected stdout (not executed): ready Common mistake: Waiting for an event without a protected predicate.

Formal Syntax & Structure

rust syntaxrust
Condvar::new(); cv.wait_while(guard, predicate)

Working Example

Example Snippetrust
fn main() {    use std::sync::{Mutex, Condvar};    let pair = (Mutex::new(false), Condvar::new());    std::thread::scope(|s| {        s.spawn(|| { *pair.0.lock().unwrap() = true; pair.1.notify_one(); });        let g = pair.1.wait_while(pair.0.lock().unwrap(), |ready| !*ready).unwrap();        assert!(*g);    });    println!("ready");}
Rust Reference