Condition Variables
A condition variable lets a thread wait until another thread says a condition might be true. It is always used with a mutex that protects the condition's data.
Detailed Explanation
A mutex stops two threads from touching data at once. It does not put a thread to sleep until "the queue is non-empty." Polling the queue under a lock wastes a core. A condition variable is the sleep.
pthread_cond_wait(&cv, &mu) atomically releases mu and sleeps. When the thread wakes, it reacquires mu before returning. pthread_cond_signal wakes one waiter. pthread_cond_broadcast wakes all. The waker should hold the mutex when it changes the condition, so the change is published with the same lock.
Waiters must loop:
while (!ready) {
pthread_cond_wait(&cv, &mu);
}
Spurious wakeups are allowed. A signal may also have been eaten by a waiter that then found the condition false again. The while re-checks under the mutex. An if is a defect.
The condition is ordinary data — a bool, a count, a queue length — protected by the mutex. The condvar is not the condition. Signaling without changing data, or changing data without signaling, is how programs hang. Signal after the write, still under the lock (or immediately after unlock; under the lock is simpler to get right).
pthread_cond_timedwait returns ETIMEDOUT if the deadline passes. Check the condition after a timeout too; the data may have changed.
Destroying a condvar that still has waiters is undefined. The same pairing as mutexes applies: static initializer PTHREAD_COND_INITIALIZER, or init / destroy.
Do not use a condvar as a semaphore by counting signals. Signals are not queued if no one is waiting. A semaphore or a count under the mutex is the state; the condvar is only the wakeup.
Code Examples
#include <pthread.h>
#include <stdio.h>
static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cv = PTHREAD_COND_INITIALIZER;
static int ready;
static void *worker(void *arg)
{
(void)arg;
pthread_mutex_lock(&mu);
while (!ready) {
pthread_cond_wait(&cv, &mu);
}
printf("go\n"); /* prints: go */
pthread_mutex_unlock(&mu);
return NULL;
}
int main(void)
{
pthread_t t;
pthread_create(&t, NULL, worker, NULL);
pthread_mutex_lock(&mu);
ready = 1;
pthread_cond_signal(&cv);
pthread_mutex_unlock(&mu);
pthread_join(t, NULL);
return 0;
}Common Gotchas
`signal` does not remember the pulse
if it happens before the waiter reaches `wait`, the waiter sleeps forever unless `ready` is already true and the `while` does not wait.
Prefer `broadcast` when more than one waiter may be able to proceed
a single `signal` plus several waiters is a lost wakeup if the wrong one runs.
Waiting with `if (!ready)` instead of `while` loses to spurious wakeups and to s
Waiting with `if (!ready)` instead of `while` loses to spurious wakeups and to stolen signals
Waiting without holding the mutex is undefined behavior
Waiting without holding the mutex is undefined behavior