Condition Variables and Predicate Loops
Wait for a shared predicate without losing notifications or assuming that a wakeup reserves the desired state.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 2
- Reading time
- 1 min
In this article2 chapters
Release the mutex as part of the wait
For a queue, a consumer first holds its mutex and checks whether an item exists. If empty, it waits using the primitive that releases the mutex and prepares to sleep as one coordinated operation. A producer can then acquire the mutex, modify the queue, and notify a waiter. Using separate uncoordinated unlock and sleep steps would create a gap in which the consumer could miss the state change.
A wakeup means recheck the predicate
When wait returns with the mutex reacquired, another consumer may already have taken the item, or the primitive may allow a spurious wakeup. A loop around the predicate handles both. Notifications and shared conditions have separate roles. Mutex invariants define how the queue state is protected. Counting semaphores can explicitly account for available items or spaces.[1][2]