Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anyone explain C code of a condition variable's signal being broadcast to all waiting threads using pthread_cond_broadcast()?

Tags:

c

Can anyone explain C code that demonstrate the use of a condition variable's signal being broadcast to all waiting threads using pthread_cond_broadcast() ?

like image 942
user1754940 Avatar asked Apr 06 '11 12:04

user1754940


1 Answers

pthread_cond_broadcast() should be used when multiple threads may be waiting on the condition variable, but some of those threads may not be ready to proceed. pthread_cond_signal() might wake up one of those threads; pthread_cond_broadcast() wakes them all, so that if any can proceed, one will.

For example, we might have a mutex protecting two variables x and y. Some threads wait on this condition:

pthread_mutex_lock(&mutex);
while (x < 10)
    pthread_cond_wait(&cond, &mutex);

whereas others wait on this condition:

pthread_mutex_lock(&mutex);
while (x < 10 || y < 5)
    pthread_cond_wait(&cond, &mutex);

If a thread increases x above 10 but leaves y less than 5, then it should use pthread_cond_broadcast(&cond), because any threads waiting on the second condition aren't ready to run yet, so we have to ensure that at least one thread from the first condition is woken (if there are any waiting on that condition).

The other situation in which pthread_cond_broadcast() can be used is when all waiting threads can proceed (eg. when a group of threads should stop waiting and exit).

One thing to keep in mind for correct code is that pthread_cond_signal() is an optimisation, nothing more - if your code is correct, then it should also work if every pthread_cond_signal() were replaced by pthread_cond_broadcast() (but perhaps not as efficiently).

like image 165
caf Avatar answered Sep 29 '22 19:09

caf