Why does it work (Mutex + condvar)

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.

From the docs:

This function will atomically unlock the mutex specified (represented by guard) and block the current thread. This means that any calls to notify_one or notify_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.

Which function?
OK, got the function, the wait function. But still, even after the unlock of the mutex, the other (the first one) thread is still locked, and how is it being notified that the mutex got unlocked by the condvar.wait method?

I linked you the docs: wait.

Yes, I got it. I've asked follow up question in this same thread.
OK, I understand now, the mutex locked in the fist thread gets unlocked by the OS.
Thank you for your help.

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.