From the official example on CondVar:
/// 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();
/// *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();
/// while !*started {
/// started = cvar.wait(started).unwrap();
/// }
AFAIA Mutexes works in the following way:
If mutex is not locked and we try to lock it, it will lock and we can continue to access the protected by that mutex resource. Let's imagine that is that first thread from the example.
If another thread tries to lock this mutex but the mutex is already locked the thread will be put to sleep. Let's imagine that is the second thread in our exampe.
And here is the lack of my understanding:
What if the second thread first locks the mutex? Then the first thread will try to lock on that mutex but because the mutex is locked by the second thread the first thread will be put to sleep. If that's so, then the second thread will never get through the while loop because the first thread is put to sleep and will not set the bool value to true. So we should have a deadlock.