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.
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.
#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;
}consumed 1 itemThe 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).