The Linux Programming Interface

(nextflipdebug5) #1

644 Chapter 30


The difference between pthread_cond_signal() and pthread_cond_broadcast() lies in
what happens if multiple threads are blocked in pthread_cond_wait(). With
pthread_cond_signal(), we are simply guaranteed that at least one of the blocked
threads is woken up; with pthread_cond_broadcast(), all blocked threads are woken up.
Using pthread_cond_broadcast() always yields correct results (since all threads
should be programmed to handle redundant and spurious wake-ups), but
pthread_cond_signal() can be more efficient. However, pthread_cond_signal() should
be used only if just one of the waiting threads needs to be woken up to handle the
change in state of the shared variable, and it doesn’t matter which one of the wait-
ing threads is woken up. This scenario typically applies when all of the waiting
threads are designed to perform the exactly same task. Given these assumptions,
pthread_cond_signal() can be more efficient than pthread_cond_broadcast(), because it
avoids the following possibility:


  1. All waiting threads are awoken.

  2. One thread is scheduled first. This thread checks the state of the shared vari-
    able(s) (under protection of the associated mutex) and sees that there is work
    to be done. The thread performs the required work, changes the state of the
    shared variable(s) to indicate that the work has been done, and unlocks the
    associated mutex.

  3. Each of the remaining threads in turn locks the mutex and tests the state of the
    shared variable. However, because of the change made by the first thread,
    these threads see that there is no work to be done, and so unlock the mutex
    and go back to sleep (i.e., call pthread_cond_wait() once more).


By contrast, pthread_cond_broadcast() handles the case where the waiting threads are
designed to perform different tasks (in which case they probably have different
predicates associated with the condition variable).
A condition variable holds no state information. It is simply a mechanism for
communicating information about the application’s state. If no thread is waiting
on the condition variable at the time that it is signaled, then the signal is lost. A
thread that later waits on the condition variable will unblock only when the variable
is signaled once more.
The pthread_cond_timedwait() function is the same as pthread_cond_wait(),
except that the abstime argument specifies an upper limit on the time that the
thread will sleep while waiting for the condition variable to be signaled.

#include <pthread.h>

int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
All return 0 on success, or a positive error number on error
Free download pdf