Search⌘ K

Condition Variables

Explore the concept of condition variables in thread programming, focusing on their use in POSIX Thread API to coordinate thread execution safely. Understand how to use pthread_cond_wait and signaling routines with associated locks, why rechecking conditions in a loop is necessary, and why simple flags are unreliable for synchronization.

We'll cover the following...

The other major component of any threads library, and certainly the case with POSIX threads, is the presence of a condition variable. Condition variables are useful when some kind of signaling must take place between threads if one thread is waiting for another to do something before it can continue. Two primary routines are used by programs wishing to interact in this way:

C
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
int pthread_cond_signal(pthread_cond_t *cond);

Usage

To use a condition variable, one has to in addition have a lock that is associated with this condition. When calling either of the above routines, this lock should be held. The first routine, pthread_cond_wait(), puts the calling thread to sleep and thus waits for some other thread to signal it, usually when something in the program has changed that the now-sleeping thread might care about. Typical usage looks like this:

C
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
Pthread_mutex_lock(&lock);
while (ready == 0)
Pthread_cond_wait(&cond, &lock);
Pthread_mutex_unlock(&lock);

In this code, after initialization of the ...