3 ms·
Semaphores are perfect for controlling the amount of concurrency. I use then for this all the time. Sure I could use a mutex and a counter plus comparison and
by pkulak 9y ago
Semaphores are perfect for controlling the amount of concurrency. I use then for this all the time.
Sure I could use a mutex and a counter plus comparison and busy wait... but why? As far as I'm concerned, a semaphore is just a more extendable mutex.
- exDM69 9y agoThere's no busy waiting involved with condition variables. The while loop is there to guard against spurious wakeups, and it is not a "busy" loop. A semaphore can be implemented using a mutex and a condition at pretty much the same cost as a "raw" semaphore. It is theoretically 2x faster (1 vs 2 atomics needed) but that isn't worth the handicap from being constrained to a single integer state. If you need two or more semaphores, it's already much worse. And even many textbook examples do (to guarantee clean exit). A semaphore is just a crippled condition variable that had only a single integer as a state. It sort-of works but isn't very practical in real world applications.