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?
wait
's documentation says (emphasis added):
pub fn wait<'a, T>( &self, guard: MutexGuard<'a, T> ) -> LockResult<MutexGuard<'a, T>>
This function will atomically unlock the mutex specified (represented by
guard
) and block the current thread. This means that any calls tonotify_one
ornotify_all
which happen logically after the mutex is unlocked are candidates to wake this thread up. When this function call returns, the lock specified will have been re-acquired.
When you call cvar.wait
inside the loop it unlocks the mutex, which allows the spawned thread to lock it and set started
to true
.