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

Waiting with pthread_cond_wait

Waiting with pthread_cond_wait

What you'll learn: How to make a thread pause efficiently until a specific condition is met, saving CPU cycles compared to constant polling.

The Problem with Busy Waiting

Imagine you are waiting for a delivery. You could stand at the front door and shout, "Is it here yet?" every single second. This works, but it’s exhausting and prevents you from doing anything else. In programming, this is called "busy-waiting" or "polling." It wastes massive amounts of CPU power.

In systems programming, we often need a thread to wait until a shared resource is ready (like a buffer having data). Instead of a loop that constantly checks a variable, we use Condition Variables.

How pthread_cond_wait Works

The function pthread_cond_wait(&cond, &mutex) is a specialized "sleep" command. It follows a very specific three-step dance that happens automatically:

  1. Release: It unlocks the mutex you are holding. This is crucial because it allows other threads to access the shared data and eventually change the condition you are waiting for.
  2. Wait: It puts the thread to sleep so it consumes zero CPU.
  3. Re-acquire: Once another thread signals that things are ready, your thread wakes up and automatically re-locks the mutex before the function returns.

The "While" Rule

You must always call pthread_cond_wait inside a while loop, not an if statement. This is because of "spurious wakeups"—sometimes threads wake up by accident, or another thread might have snatched the resource in the millisecond after yours woke up. The loop ensures you re-verify the condition.

#include <pthread.h>

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
int ready = 0;

void* wait_for_data(void* arg) {
    pthread_mutex_lock(&lock);
    
    // Use a while loop to check the condition
    while (ready == 0) {
        // This sleeps and unlocks 'lock'
        // When it returns, 'lock' is owned by us again
        pthread_cond_wait(&condition, &lock);
    }
    
    // Now we safely own the lock and ready is 1
    pthread_mutex_unlock(&lock);
    return NULL;
}

Why the Mutex is Required

You cannot use a condition variable without a mutex. The mutex protects the "ready" flag itself. If you didn't have the mutex, a "race condition" could occur where the signaling thread sends its notification right before the waiting thread goes to sleep, causing the waiting thread to sleep forever.

Key takeaway

pthread_cond_wait allows a thread to sleep efficiently by releasing a mutex and only re-acquiring it once a specific signal is received.