Why use binary semaphores when the same functionality can be achieved with a simple variable ?
Because a semaphore isn't a simple variable, it's a larger construct than that.
Specifically, with a counting semaphore (which a binary semaphore is, effectively, with a count of 1), there's the added capability of blocking any process/thread that tries to increment the semaphore above its maximum value.
Semaphores also have the additional facility that their state is changed "atomically", which means that the underlying memory is surrounded by logic to ensure that the CPU caches and such are flushed, and that when the value is changed, it's changed for "everyone". This is particularly important on modern multi-core processors.
The semaphore is appropriate to use when you are trying to guard a shared resource from over use. A binary semaphore is perfect for resources that can only be used by one process/thread at a time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With