How To Use Condition Variable

Majid Azimi picture Majid Azimi · Jun 1, 2011 · Viewed 7.3k times · Source

The Linux Programming Interface book has a piece of code (producer/consumer) to show how condition variable works:

static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

static int avail = 0;

while (TRUE) {
    s = pthread_mutex_lock(&mtx);

    while (avail == 0) {   /* Wait for something to consume */
       s = pthread_cond_wait(&cond, &mtx);
    }

    while (avail > 0) {   /* Consume all available units */ 
        avail--;
    }

    s = pthread_mutex_unlock(&mtx);
}

Why we use pthread_mutex_lock in while? why we don't use it in an if?

Answer

Nemo picture Nemo · Jun 1, 2011

Because pthread_cond_signal() is allowed to wake up more than one thread waiting on the condition variable. Therefore you must double-check the condition once you wake up, because some other thread might have woken up and changed it ahead of you.

If you know you have just one thread waiting, and you are sure nobody in the future will ever modify code elsewhere in the program to add another thread waiting, then you can use if. But you never know that for sure, so always use while.

[update]

As ninjalj points out in a comment, my answer is incomplete for failing to mention "spurious wakeups". For example, the POSIX standard makes it clear that if the waiting thread receives a signal (e.g. via kill()), pthread_cond_wait() can return 0 even if no other thread signaled the condition variable. The standard is ambiguous (in my view) as to whether the waiting thread can be woken up for no reason at all... But the bottom line is: Always use while, not if.