Skip to content
systemcoding.dev
Concurrency

Wake one waiting thread with pthread_cond_signal

Wake a single waiter with pthread_cond_signal after changing shared state under the mutex, and recheck the predicate in a loop on glibc 2.39.

1 min read
Summarize in AI

A condition variable lets a thread sleep until another thread changes some state. The waiter holds the mutex, checks the predicate, and calls pthread_cond_wait, which atomically releases the mutex and sleeps. The producer changes the state under the same mutex and calls pthread_cond_signal to wake one waiter. GCC 13, glibc 2.39, -pthread.

signal.cc
#include <pthread.h>
#include <stdio.h>

static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t  cv = PTHREAD_COND_INITIALIZER;
static int items;

static void *consumer(void *arg)
{
    (void)arg;
    pthread_mutex_lock(&m);
    while (items == 0)
        pthread_cond_wait(&cv, &m);
    items--;
    pthread_mutex_unlock(&m);
    puts("consumed 1 item");
    return NULL;
}

int main(void)
{
    pthread_t t;
    pthread_create(&t, NULL, consumer, NULL);

    pthread_mutex_lock(&m);
    items++;
    pthread_mutex_unlock(&m);
    pthread_cond_signal(&cv);

    pthread_join(t, NULL);
    return 0;
}
Text
consumed 1 item

The while loop is required: a waiter can wake without a signal, and between the signal and the wake-up another thread may have taken the item. A signal sent when nobody waits is lost, which is why the state lives in items and not in the signal. Signalling after unlocking, as here, is allowed and avoids waking a thread that immediately blocks on the mutex. See pthread_cond_signal(3p).

Taggedcpthreads
Share

More snippets

Get new posts by email

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

Unsubscribe in one click. No spam, ever.