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
  1. Release the mutex as part of the wait
  2. A wakeup means recheck the predicate

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]

References

  1. Remzi H. Arpaci-Dusseau and Andrea C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces ↩
  2. Maurice Herlihy and Nir Shavit, The Art of Multiprocessor Programming ↩