From here: https://computing.llnl.gov/tutorials/pthreads/#ConVarSignal
Note that the pthread_cond_wait
routine will automatically and atomically unlock mutex while it waits.
The following sub-code is from the same link (formatting by me):
pthread_mutex_lock(&count_mutex);
while (count<COUNT_LIMIT)
{
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %ld Condition signal received.\n", my_id);
count += 125;
printf("watch_count(): thread %ld count now = %d.\n", my_id, count);
}
pthread_mutex_unlock(&count_mutex);
Question:
When it says that pthread_cond_wait will automatically unlock mutex while it waits, then why do we have to explicitly specify the function pthread_mutex_unlock at the end of the code above?
What’s the point that I am missing?
When
pthread_cond_waitunblocks it is holding the lock again. Say for example you go around the loop twice you get the following sequence of lock/unlocks on the mutex:If you don’t have that last unlock there then you’ll end up with deadlock the next time someone else wants to acquire the lock.