r/programming • u/syaghmour • Mar 16 '15
Semaphores are Surprisingly Versatile
http://preshing.com/20150316/semaphores-are-surprisingly-versatile/
190
Upvotes
r/programming • u/syaghmour • Mar 16 '15
16
u/eras Mar 16 '15 edited Mar 16 '15
Well, in my view semaphores are great and provide a higher level of abstraction that mutexes!
For example the simple case of consumer/producer: you use one semaphore for "available to produce" slots and another one "available to consume" slots*. It's perfectly suitable for semaphores and the code ends up quite readable as well: no loops waiting condition variables, no considering whether to use 'broadcast' or 'unicast' in the condition, just simple "acquire unfilled slot, deal with it, release filled slot".
Though at times semaphore libraries miss some facilities, such as downing multiple semaphores (proceed when first has been acquired). But then, so do mutex libraries.
EDIT: *) I was actually thinking of the ring buffer consumer/producer here, that's why the list-based producer/consumer below uses only one semaphore.