Skip to content
systemcoding.dev
Concurrency

Wait for Conditions with pthread_cond_wait

Make a C thread sleep until another signals that work is ready with pthread_cond_wait, pthread_cond_signal and a predicate loop on Linux with glibc 2.41.

8 min read
Summarize in AI
Flat illustration of parallel threads meeting at a mutex, with the C, C++ and Erlang logos.

A mutex answers "who may touch this data right now". It does not answer "when is there something worth touching". A worker thread that wants a job from a shared list has two bad options: spin in a loop that burns a core, or sleep for a guessed interval and add latency. The right tool is a condition variable, pthread_cond_t. The consumer sleeps without using CPU, the producer wakes it exactly when state changes, and a mutex guards the state in between. This post builds the smallest correct example in C with POSIX threads on Linux, glibc 2.41 and GCC 14, and spends most of its time on the three rules that people break. The pitfall that follows from the wake-up behavior has its own post in this cluster.

What a condition variable is

A condition variable is a queue of sleeping threads. It stores no value and no flag. Three operations matter:

  • pthread_cond_wait(&cond, &mutex) atomically unlocks the mutex and puts the calling thread to sleep on cond. When it wakes, it relocks the mutex before returning.

  • pthread_cond_signal(&cond) wakes at least one thread waiting on cond, if any.

  • pthread_cond_broadcast(&cond) wakes all of them.

The word "atomically" in the first item is the whole reason the API exists. Without it, a thread could unlock the mutex, then a signal could arrive before the thread started sleeping, and the wake-up would be lost forever. The POSIX specification requires pthread_cond_wait to release the mutex and block as one step.

A signal is not remembered. If no thread is waiting when pthread_cond_signal runs, nothing happens, and a thread that starts waiting afterward sleeps until the next signal. That is why a condition variable is always paired with real shared state that records whether the event already happened.

The shape of every correct wait

The condition variable never holds the condition. A variable you own does, and the wait is a loop that rechecks it.

c
pthread_mutex_lock(&m);
while (!condition_is_true)
    pthread_cond_wait(&cond, &m);
/* condition is true and m is held */
pthread_mutex_unlock(&m);

Three rules sit in those four lines.

  1. Hold the mutex when you call pthread_cond_wait. Calling it without the lock is undefined behavior.

  2. Test the condition under the same mutex that the signaling thread uses when it changes the condition.

  3. Wait in a while loop, not an if. A thread can wake without the condition being true, and the loop covers that.

A complete example: a ready flag

The smallest useful program has one thread wait for another to finish setup.

ready.cc
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t  ready_cv = PTHREAD_COND_INITIALIZER;
static int ready = 0;

static void *waiter(void *arg) {
    (void)arg;
    pthread_mutex_lock(&lock);
    while (!ready)
        pthread_cond_wait(&ready_cv, &lock);
    pthread_mutex_unlock(&lock);
    printf("waiter: saw ready\n");
    return NULL;
}

static void *setter(void *arg) {
    (void)arg;
    sleep(1);                       /* pretend to initialize something */
    pthread_mutex_lock(&lock);
    ready = 1;
    pthread_cond_signal(&ready_cv);
    pthread_mutex_unlock(&lock);
    printf("setter: signaled\n");
    return NULL;
}

int main(void) {
    pthread_t w, s;
    pthread_create(&w, NULL, waiter, NULL);
    pthread_create(&s, NULL, setter, NULL);
    pthread_join(w, NULL);
    pthread_join(s, NULL);
    return 0;
}

Build with gcc -pthread ready.c -o ready and run it. After about a second:

Text
setter: signaled
waiter: saw ready

The two printed lines can come out in either order, because the waiter prints after it is woken and the setter prints after it unlocks. What cannot vary is that the waiter does not print before the flag is set. If the waiter started second, after the setter had already finished, it would find ready equal to 1, skip the loop and never wait at all. That is the flag doing the work the condition variable cannot do: remembering that the event happened.

Waiting on a queue

The more common use is a work queue. Producers add items and signal, consumers wait until the queue is non-empty.

jobs.cc
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

struct job {
    int id;
    struct job *next;
};

static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t  not_empty = PTHREAD_COND_INITIALIZER;
static struct job *head = NULL;
static int done = 0;

static void submit(int id) {
    struct job *j = malloc(sizeof *j);
    j->id = id;
    pthread_mutex_lock(&lock);
    j->next = head;
    head = j;
    pthread_cond_signal(&not_empty);
    pthread_mutex_unlock(&lock);
}

static void finish(void) {
    pthread_mutex_lock(&lock);
    done = 1;
    pthread_cond_broadcast(&not_empty);
    pthread_mutex_unlock(&lock);
}

static void *worker(void *arg) {
    (void)arg;
    for (;;) {
        pthread_mutex_lock(&lock);
        while (head == NULL && !done)
            pthread_cond_wait(&not_empty, &lock);
        if (head == NULL && done) {
            pthread_mutex_unlock(&lock);
            return NULL;
        }
        struct job *j = head;
        head = j->next;
        pthread_mutex_unlock(&lock);

        printf("processed job %d\n", j->id);
        free(j);
    }
}

int main(void) {
    pthread_t w;
    pthread_create(&w, NULL, worker, NULL);
    for (int i = 1; i <= 3; i++)
        submit(i);
    finish();
    pthread_join(w, NULL);
    return 0;
}
Text
processed job 3
processed job 2
processed job 1

The list is a stack, so the last job submitted is processed first, and with a single worker that is racing the submissions, the exact interleaving of jobs 1 to 3 can vary: the worker may take job 1 before job 2 is added. Treat the order shown as one possible run. What the example demonstrates is the loop condition head == NULL && !done. The worker sleeps while there is nothing to do and nothing more is coming, and wakes on either a new job or the shutdown. finish uses pthread_cond_broadcast because shutdown must reach every waiting worker, not just one.

Signal inside or outside the lock

You will see both pthread_cond_signal before and after pthread_mutex_unlock. Both are correct. POSIX permits signaling without holding the mutex, and doing it after unlock can avoid waking a thread that immediately blocks on the mutex you still hold. The cost is that if you change the condition and signal after unlocking, you must still have changed the condition under the lock. Signaling inside the lock is simpler to reason about and is where to start.

Timed waits

When a thread must not wait forever, use pthread_cond_timedwait, which takes an absolute deadline as a struct timespec and returns ETIMEDOUT if it passes. By default the clock is CLOCK_REALTIME, which can jump when the system time is adjusted. To use the monotonic clock, set the attribute with pthread_condattr_setclock(&attr, CLOCK_MONOTONIC) when you initialize the condition variable, then compute the deadline from clock_gettime(CLOCK_MONOTONIC, ...).

timed.cc
#include <errno.h>
#include <pthread.h>
#include <time.h>

int wait_ready(pthread_mutex_t *m, pthread_cond_t *cv, int *flag, int seconds) {
    struct timespec deadline;
    clock_gettime(CLOCK_REALTIME, &deadline);
    deadline.tv_sec += seconds;

    int rc = 0;
    pthread_mutex_lock(m);
    while (!*flag && rc != ETIMEDOUT)
        rc = pthread_cond_timedwait(cv, m, &deadline);
    int ok = *flag;
    pthread_mutex_unlock(m);
    return ok ? 0 : -1;
}

The loop still rechecks the flag. A timeout wakes the thread, and so can a real signal, and only the flag says which happened. If the flag is set at the moment of timeout, the function reports success, which is correct.

Common mistakes

Using if in place of while works in tests and fails rarely, which is the worst kind of failure. Signaling without changing any state first leaves the waiter to loop straight back to sleep. Waiting on one condition variable with two different mutexes is undefined behavior: every thread that waits on a condition variable at the same time must use the same mutex. And destroying a condition variable while threads still wait on it is also undefined.

Why not just poll

The alternative to a condition variable is a loop that checks a flag and sleeps for a short interval. It works, and it has two costs. A polling thread wakes up many times for nothing, which keeps a core out of its idle states and adds measurable power use on a laptop or a battery device. And the delay between the event and the reaction is up to one polling interval, so a shorter interval trades latency for wasted wake-ups. A condition variable removes the trade: the thread sleeps in the kernel with no timer, and the signaling thread wakes it directly. On Linux the glibc implementation parks the waiting thread with the futex system call, so an idle waiter consumes no CPU at all.

Polling is still reasonable in two cases. If the event source is not a thread of your program, such as a file appearing on disk, you cannot signal a condition variable and need poll, epoll or inotify instead. And if the check is nearly free and the wait is expected to last microseconds, a short spin avoids a system call. Neither applies to one thread handing work to another, which is exactly what condition variables are for.

Debugging a wait that never returns

When a thread hangs inside pthread_cond_wait, the cause is almost always one of three things. The predicate was never set, because the signaling code path was skipped by an early return or an error. The signal was sent before the thread started waiting and the predicate was not checked first, which means the code lacks the flag that the first example had. Or the waiter and the signaler used different condition variables or different mutexes by mistake.

Attach with gdb -p <pid> and run thread apply all bt. A thread blocked in a condition wait shows a frame in pthread_cond_wait or __futex_abstimed_wait_common, and the frame above it shows your function and line. Check that the signaler ran by adding a log line right after it sets the predicate. If the log line appears and the waiter still sleeps, print the predicate in the debugger from the waiter's frame: if it is true, the wait was entered without checking it first.

Share

Keep reading

Flat illustration of two options weighed side by side, with the C, C++ and Rust logos.
Performance

Spinlocks vs Mutexes: When Spinning Wins

A spinlock burns a core while it waits and a mutex sleeps. Compare their costs, write a correct C11 spinlock, and see when user-space spinning beats a mutex.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.