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

Signaling with pthread_cond_signal

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

  1. The Mutex Matters: You should generally hold the mutex when calling pthread_cond_signal to ensure the "signaler" and the "waiter" don't have a race condition regarding the state change.
  2. One at a Time: pthread_cond_signal only 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.
  3. The "Spurious" Wakeup: Sometimes, due to OS quirks, a thread might wake up without a signal. This is why we always use a while loop to check our condition again after waking up, rather than a simple if.

Key takeaway

Use pthread_cond_signal to wake up a single waiting thread after you have updated a shared resource they are interested in.