I am currently learning OS with Operating Systems : Three Easy Pieces And it introduces pthread_cond_wait() function, which makes caller of it sleep.
And It said, it unlock the mutex right after it is called and then makes caller sleep.
I have no idea why it unlock the mutex after it is called. Why is that? Please help me understand for this reason. Thank you.
A thread calls pthread_cond_wait()
when needs to wait for the value of some shared state to change. That shared state must be protected by a mutex, and pthread_cond_wait()
must unlock the mutex so another thread has the opportunity to acquire the mutex and modify the shared state - otherwise, you would have a deadlock.
The thread must hold the mutex when it calls pthread_cond_wait()
, because otherwise another thread would have the opportunity to acquire the mutex and change the shared state before the waiting thread sleeps - this is a "missed wakeup".