Working with CondVar

Why calling notify_all on condvar doesn't notify any of them?

use std::sync::{Arc, Condvar, Mutex};

fn main() {
    let holy_trinity = Arc::new((Mutex::new(()), Condvar::new()));
    let holy_trinity_clone_1 = holy_trinity.clone();
    let holy_trinity_clone_2 = holy_trinity.clone();
    let holy_trinity_clone_3 = holy_trinity.clone();
    let t0_handle = std::thread::spawn(move || {
        let (guard, cond) = &*holy_trinity;
        let mut guard_locked = guard.lock().unwrap();
        cond.notify_all();
    });
    t0_handle.join();

    let t1_handle = std::thread::spawn(move || {
        println!("Spawn thread t1_handle");
        let (guard, cond) = &*holy_trinity_clone_1;
        let mut guard_locked = guard.lock().unwrap();
        guard_locked = cond.wait(guard_locked).unwrap();
        println!("Exiting thread t1_handle");
    });

    let t2_handle = std::thread::spawn(move || {
        println!("Spawn thread t2_handle");
        let (guard, cond) = &*holy_trinity_clone_2;
        let mut guard_locked = guard.lock().unwrap();
        guard_locked = cond.wait(guard_locked).unwrap();
        println!("Exiting thread t2_handle");
    });

    let t3_handle = std::thread::spawn(move || {
        println!("Spawn thread t3_handle");
        let (guard, cond) = &*holy_trinity_clone_3;
        let mut guard_locked = guard.lock().unwrap();
        guard_locked = cond.wait(guard_locked).unwrap();
        println!("Exiting thread t3_handle");
    });

    t1_handle.join();
    t2_handle.join();
    t3_handle.join();
    println!("Hello, world!");
}

The notify_all call has to happen after the wait call for it to have an effect.

2 Likes

Thank you, that clears it.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.