Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why semaphore?

Why use binary semaphores when the same functionality can be achieved with a simple variable ?

like image 418
Onkar Mahajan Avatar asked Dec 09 '22 12:12

Onkar Mahajan


1 Answers

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.

like image 110
Will Hartung Avatar answered Dec 21 '22 23:12

Will Hartung