andersch.dev

<2025-04-14 Mon>

Condition Variable

Condition variables are synchronization primitives used in multithreading that allow threads to wait until a condition is met. During this time, threads are suspended (sleeping), which avoids busy waiting (spinning).

They are typically used alongside mutexes to solve the producer-consumer problem and similar synchronization scenarios.

Usage:

Basic Condition Variable API

int cond_init(cond_t **cond);
int cond_wait(cond_t *cond, mutex_t *mutex);
int cond_timedwait(cond_t *cond, mutex_t *mutex, uint64_t timeout_ms);
int cond_signal(cond_t *cond);    // awaken single waiting thread
int cond_broadcast(cond_t *cond); // awaken all waiting threads
int cond_destroy(cond_t *cond);