pthread_cond_wait and mutex requirement

前端 未结 3 735
悲哀的现实
悲哀的现实 2020-12-23 10:41

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

3条回答
  •  粉色の甜心
    2020-12-23 11:05

    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.

提交回复
热议问题