https://doc.rust-lang.org/stable/std/sync/struct.Condvar.html
use std::sync::{Arc, Mutex, Condvar};
use std::thread;
let pair = Arc::new((Mutex::new(false), Condvar::new()));
let pair2 = Arc::clone(&pair);
// Inside of our lock, spawn a new thread, and then wait for it to start.
thread::spawn(move|| {
let (lock, cvar) = &*pair2;
let mut started = lock.lock().unwrap(); // #1
*started = true;
// We notify the condvar that the value has changed.
cvar.notify_one();
});
// Wait for the thread to start up.
let (lock, cvar) = &*pair;
let mut started = lock.lock().unwrap(); // #2
while !*started {
started = cvar.wait(started).unwrap();
}
If I understand this correctly, the core in the spawned thread (#1
) might run after the main thread locked the mutex (#2
). But in this case, the main thread will never unlock it, because the spawned thread can't lock it and change the value, so the loop keeps running forever... Or, is it because of some Condvar
mechanics?