开发者

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

Can anyone explain C code t开发者_运维问答hat demonstrate the use of a condition variable's signal being broadcast to all waiting threads using pthread_cond_broadcast() ?


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜