2

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?

1 Answer 1

4

When pthread_cond_wait unblocks 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:

lock # Around loop twice: wait (unlock) awaken (holding lock) wait (unlock) awaken (holding lock) # loop done, still holding lock unlock 

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I missed this statement from the same link: computing.llnl.gov/tutorials/pthreads/#ConVarSignal "After signal is received and thread is awakened, mutex will be automatically locked for use by the thread. The programmer is then responsible for unlocking mutex when the thread is finished with it. Got your point now, thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.