Why it is required to lock a mutex before calling pthread_cond_wait
?
Also, is it required to take a lock (on the same mutex) before calling pthrea
The whole point of condition variables is to allow threads to be notified of changes on data structures protected by a mutex, e.g. you may want to be notified when a queue is no longer empty, so you atomically release the mutex and wait on the condition variable, and when a new element is queued, you are awaken and take the mutex to process the new element.
Unlike Java's monitors, pthread_cond_{signal,broadcast}()
doesn't need to hold the mutex. A signalling of a condition variable when no thread is waiting on that condition variable is lost, but that shouldn't make that much of a difference, since the signal could also be lost if the producer starts running before the consumer.