Page 1 of 1

pthread_cond_wait automatically and atomically unlocks mutex

Posted: Sat Jun 16, 2012 5:01 am
by AnishaKaul
From here: https://computing.llnl.gov/tutorials/pt ... nVarSignal
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):

Code: Select all

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?

Re: pthread_cond_wait automatically and atomically unlocks m

Posted: Sat Jun 16, 2012 5:09 am
by iansjack
The full quote from that link is
pthread_cond_wait() blocks the calling thread until the specified condition is signalled. This routine should be called while mutex is locked, and it will automatically release the mutex while it waits. 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.
Does the bit that I have emboldened not explain this?

Re: pthread_cond_wait automatically and atomically unlocks m

Posted: Sat Jun 16, 2012 5:14 am
by AnishaKaul
:redface:

I didn't read beyond that quoted statement. Wanted to be sure of what that statement was talking about first of all.
My fault. Will be more careful in future.

Re: pthread_cond_wait automatically and atomically unlocks m

Posted: Sat Jun 16, 2012 5:42 am
by AnishaKaul
I read the official man page for `pthread_cond_wait` in detail, but surprisingly didn't find anything w.r.t
the programmer is then responsible for unlocking mutex when the thread is finished with it.
http://linux.die.net/man/3/pthread_cond_wait

but now I think I've got the point:
The `pthread_cond_wait` unlocks mutex when the thread starts waiting.
When the `pthread_cond_wait` receives the signal, the mutex is locked again for that particular thread.

So, now the thread is
- "out of the waiting state",
- owns the mutex,
- executes the desired code (written "after" the wait statement),

so, now obviously we'll have to provide the unlocking mechanism for that thread.