Reputation: 157
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.
Upvotes: 1
Views: 149
Reputation: 239011
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".
Upvotes: 0
Reputation: 73041
If it left the mutex locked while the caller slept, then no other thread would be able to acquire the mutex until after pthread_cond_wait() returned and the caller woke up and explicitly unlocked the mutex. That behavior would be difficult to work with, since if the mutex is also being used to serialize access to some data, then no other thread would be able to safely read or write that data while the first thread was asleep (since if it did so without locking the mutex, that would introduce a race condition, and if it tried to lock the mutex, the program would deadlock).
Upvotes: 2