Signaling with pthread_cond_signal
What you'll learn: How to use signaling to wake up a specific thread that is waiting for a condition to change.
The Sleeping Guard
In previous lessons, we learned that pthread_cond_wait puts a thread to sleep while it waits for a specific condition (like a queue filling up). But a sleeping thread is like a guard taking a nap; it won't wake up on its own just because the situation changed. It needs a "poke" from another thread.
In C, that poke is pthread_cond_signal. When one thread finishes a task that others are waiting for, it calls this function to wake up exactly one thread currently blocked on that condition variable.
How Signaling Works
Think of a coffee shop. A customer (Thread A) sits in a chair and goes to sleep because there are no donuts left. The baker (Thread B) arrives later, puts a donut on the counter, and rings a bell.
The bell is pthread_cond_signal. It doesn't tell the customer what happened; it just wakes them up so they can open their eyes and check the counter themselves.
#include <pthread.h>
#include <stdio.h>
int donuts_available = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void* baker(void* arg) {
pthread_mutex_lock(&lock);
donuts_available += 1;
printf("Baker: Made a donut! Signaling...\n");
// Wake up one thread waiting on this condition
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
return NULL;
}
void* customer(void* arg) {
pthread_mutex_lock(&lock);
while (donuts_available == 0) {
printf("Customer: No donuts. Going to sleep...\n");
pthread_cond_wait(&cond, &lock);
}
donuts_available--;
printf("Customer: Got my donut!\n");
pthread_mutex_unlock(&lock);
return NULL;
}
Important Rules
- The Mutex Matters: You should generally hold the mutex when calling
pthread_cond_signalto ensure the "signaler" and the "waiter" don't have a race condition regarding the state change. - One at a Time:
pthread_cond_signalonly wakes up one thread. If five threads are waiting, the other four will stay asleep. If no threads are waiting, the signal is simply discarded. - The "Spurious" Wakeup: Sometimes, due to OS quirks, a thread might wake up without a signal. This is why we always use a
whileloop to check our condition again after waking up, rather than a simpleif.
Key takeaway
Use pthread_cond_signal to wake up a single waiting thread after you have updated a shared resource they are interested in.