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:
- Thread atomically releases a mutex and enters wait state
- Waiting thread awakens by signal (one thread) or broadcast (all threads)
- Upon waking, thread reacquires mutex before proceeding
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);