Course contentsShow
← C
Lesson 1132 of 1,21915. Systems ProgrammingFree lesson

Introduction to condition variables

Introduction to condition variables

What you'll learn: How to use condition variables to let threads sleep efficiently until a specific state changes, saving CPU resources.

The "Are we there yet?" problem

Imagine you are driving a car while a passenger in the back seat asks, "Are we there yet?" every five seconds. In programming, this is called busy-waiting. A thread sits in a while loop, constantly checking a variable. This works, but it wastes massive amounts of CPU power because the thread never stops running, even though it can't proceed.

A Condition Variable (CV) is the solution. It is a signaling mechanism that allows a thread to say, "I’m going to sleep now. Wake me up only when this specific thing happens."

How it works

Condition variables work in tandem with a Mutex. The mutex protects the shared data, while the condition variable handles the "waiting" part.

When a thread waits on a condition variable, it atomically releases the mutex and goes to sleep. When another thread changes the data and "signals" the condition variable, the sleeping thread wakes up and automatically re-acquires the mutex before continuing.

Seeing it in code

In C, we use pthread_cond_wait to sleep and pthread_cond_signal to wake someone up.

#include <pthread.h>

int fuel = 0; // Shared resource
pthread_mutex_t mutex_fuel = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_fuel = PTHREAD_COND_INITIALIZER;

void* consumer(void* arg) {
    pthread_mutex_lock(&mutex_fuel);
    
    // We use a while loop to handle "spurious wakeups"
    while (fuel < 10) {
        // Sleep and release mutex. Re-locks when signaled.
        pthread_cond_wait(&cond_fuel, &mutex_fuel);
    }
    
    fuel -= 10;
    pthread_mutex_unlock(&mutex_fuel);
    return NULL;
}

void* producer(void* arg) {
    pthread_mutex_lock(&mutex_fuel);
    fuel += 10;
    // Notify the waiting thread that the state has changed
    pthread_cond_signal(&cond_fuel);
    pthread_mutex_unlock(&mutex_fuel);
    return NULL;
}

Why use a while loop?

Notice the while (fuel < 10)? Threads can sometimes wake up for no reason (called a spurious wakeup) or another thread might grab the fuel first. Always re-check your condition immediately after waking up to ensure it is actually safe to proceed.

Key takeaway

Condition variables allow threads to wait for specific conditions to become true without wasting CPU cycles by constantly polling.