Condvar Wait Timeout Deadline

Bound a condition wait with Condvar::wait_timeout_while so a missing notification becomes a deadline instead of a hung thread.

RustResilience

Code

rustsnippet
37 lines
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use std::time::Duration;

fn main() {
    let state = Arc::new((Mutex::new(false), Condvar::new()));

    let waiter = {
        let state = Arc::clone(&state);
        thread::spawn(move || {
            let (lock, condvar) = &*state;
            let ready = lock.lock().unwrap();
            // wait_timeout_while returns on notification or deadline
            let (guard, result) = condvar
                .wait_timeout_while(ready, Duration::from_millis(50), |ready| !*ready)
                .unwrap();
            (*guard, result.timed_out())
        })
    };

    thread::sleep(Duration::from_millis(10));
    {
        let (lock, condvar) = &*state;
        *lock.lock().unwrap() = true;
        condvar.notify_one();
    }
    println!("notified: {:?}", waiter.join().unwrap());

    // without a notification the same wait reports a timeout
    let lone = Arc::new((Mutex::new(false), Condvar::new()));
    let (lock, condvar) = &*lone;
    let guard = lock.lock().unwrap();
    let (_guard, result) = condvar
        .wait_timeout_while(guard, Duration::from_millis(10), |ready| !*ready)
        .unwrap();
    println!("timed out: {}", result.timed_out());
}

How the snippet works

The code’s whole job belongs to the function main.

Watch out for

  • The environment needs no preparation beyond having the interpreter or compiler.

Applying it

The main signature reads fn main()

The file announces its steps in the output: notified:, timed out:.

Statements that matter

let ready = lock.lock().unwrap();
let guard = lock.lock().unwrap();

Interactive Tools for This Topic

FAQ

What does Condvar Wait Timeout Deadline print when run?
Running the file directly is enough — expect labeled output lines such as `notified:`, `timed out:`.