Wait and Signal Operations
What you'll learn: How wait() and signal() operations on condition variables enable threads to coordinate by pausing and waking each other.
The Core Idea
Condition variables provide two fundamental operations: wait() and signal(). Think of a condition variable as a waiting room where threads can pause until another thread announces that something important has changed.
- wait(): A thread calling
wait()on a condition variable releases its associated mutex and goes to sleep atomically. The thread joins the waiting queue until it's woken up. - signal(): A thread calling
signal()wakes up one waiting thread (if any exist). The awakened thread will then reacquire the mutex before continuing.
How They Work Together
Imagine a parking lot attendant (thread A) waiting for a car to arrive. Instead of constantly checking (busy-waiting), the attendant calls wait() — going to sleep and releasing the gate lock. When a driver (thread B) arrives and parks, they call signal() to wake the attendant, who then reacquires the lock and processes the car.
The critical detail: wait() atomically releases the mutex and sleeps. This prevents race conditions where a signal might be missed between unlocking and sleeping.
Basic Pattern
// Thread waiting for a condition
pthread_mutex_lock(&mutex);
while (!condition_is_true) {
pthread_cond_wait(&cond_var, &mutex); // Releases mutex, sleeps
}
// Condition now true, mutex reacquired
pthread_mutex_unlock(&mutex);
// Thread signaling a change
pthread_mutex_lock(&mutex);
condition_is_true = 1;
pthread_cond_signal(&cond_var); // Wake one waiter
pthread_mutex_unlock(&mutex);
Key Takeaway: wait() atomically releases a mutex and sleeps until signaled, while signal() wakes a waiting thread—enabling efficient thread coordination without busy-waiting or race conditions.