Counting Semaphores and Bounded Buffers

Account for free slots and available items separately and use a mutex for the buffer representation itself.

Source
Anbloq
Language
English
Created
Updated
Chapters
2
Reading time
1 min
In this article2 chapters
  1. Credits track what can be reserved
  2. Reservation is distinct from updating the data structure

Credits track what can be reserved

With a capacity-\(N\) buffer, start an empty-slots semaphore at \(N\) and an available-items semaphore at zero. A producer waits for a free slot, inserts an item and then posts an available item. A consumer waits for an item, removes it and posts a free slot. While a producer or consumer holds a reservation, its slot may be counted by neither semaphore. The total includes those in-flight reservations.

Reservation is distinct from updating the data structure

A mutex can protect shared indices manipulated by simultaneous producers and consumers. Never block waiting for a reservation while holding a mutex needed by the thread that would release it. Cancellation must return a reserved credit or complete the corresponding operation. Condition variables instead wait on a state predicate. Backpressure generalizes bounded credits to pipelines of operators.[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 ↩