Reputation: 109
According to the man page, pthread_cond_broadcast wakes up all the threads that are waiting on condition variable (condvar). And those waken threads will hold back the mutex lock and return from pthread_cond_wait.
But what I am confusing is: Isn't it the mutex lock should held by only one thread in the same time?
Thanks in advance.
Upvotes: 1
Views: 253
Reputation: 182649
Condition variables work like this:
/* Lock a mutex. */
pthread_mutex_lock(&mtx);
/* Wait on condition variable. */
while (/* condition *.)
pthread_cond_wait(&cond, &mtx);
/* When pthread_cond_wait returns mtx is atomically locked. */
/* ... */
/* Unlock the mutex. */
pthread_mutex_unlock(&mtx);
So the main point to understand is that many threads can wake up when a broadcast is sent, but only one will "win" the race and actually lock mtx
and get out of the loop.
Upvotes: 2