Part 4 of 7 · 2 min read
Condition variables
In plain words: The worker above needs a way to wait for work without wasting the processor. Looping with while (count == 0) { } would keep a processor busy doing nothing, which is called busy waiting. A condition variable lets a thread sleep until another thread signals that something changed.
The pattern has three rules:
- A thread holds the mutex when it checks the condition and calls
pthread_cond_wait. pthread_cond_wait(&cond, &lock)atomically releases the mutex and puts the thread to sleep. When it is woken, it takes the mutex again before returning.- The wait is always inside a
whileloop that rechecks the condition, not anif. A woken thread may find that another thread already took the item, and the system is also allowed to wake a thread without any signal, which is called a spurious wake-up.
The other side calls pthread_cond_signal to wake one waiting thread, or pthread_cond_broadcast to wake all of them. The pool uses two condition variables: not_empty for workers waiting for tasks, and not_full for the submitter waiting for room. At shutdown, main sets done and broadcasts, so every sleeping worker wakes up, sees the flag and returns.
A sleeping thread is in the waiting state of Level 1, page 2. It takes no processor time until it is signalled.
Common mistake
Using if instead of while around pthread_cond_wait. After a wake-up the condition may no longer hold, and the thread would take an item from an empty queue.
Condition variable
A condition variable is a synchronisation object that lets a thread, while holding a mutex, wait until another thread signals that some condition may have become true. The wait releases the mutex and sleeps; on wake-up it takes the mutex again.
Example: a worker waits on not_empty while the queue is empty, and the producer signals not_empty after adding a task.
Check yourself:
1. What does pthread_cond_wait do with the mutex?
2. Why is the wait inside a while loop?
3. What does pthread_cond_broadcast do?