I m using pthread_cond_wait(&cond_t, &mutex);
in my program and I m wondering why this function needs as a second parameter a mutex variable.
Does the pthread_cond_wait()
unlock the mutex at the beginning (beginning of the execution pthread_cond_wait()
) and then locked when it finishes (just before leaving pthread_cond_wait()
)?
When the first thread calls pthread_cond_wait(&cond_t, &mutex);
it releases the mutex and waits until condition cond_t
is signaled as complete and mutex
is available.
So when pthread_cond_signal
is called in the other thread, it doesn't "wake up" the thread that waits yet. mutex
must be unlocked first, only then there is a chance that the first thread will get a lock, which means that "upon successful return of pthread_cond_wait
the mutex shall have been locked and shall be owned by the calling thread."