What are the practical uses of semaphores?

NoSenseEtAl picture NoSenseEtAl · Feb 12, 2014 · Viewed 13.3k times · Source

Nonbinary ones..
I have never encountered a problem that required me to use a semaphore instead of mutex. So is this mostly theoretical construct, or real sw like Office, Firefox have places where they use it? If so what are the common use patterns for semaphores?

Answer

Bob Dalgleish picture Bob Dalgleish · Feb 19, 2014

Non-binary semaphores are used in resource allocation. A semaphore might hold the count of the number of a particular resource.

If you have a pool of connections, such as a web browser might use, then an individual thread might reserve a member of the pool by waiting on the semaphore to get a connection, uses the connection, then releases the connection by releasing the semaphore.

You can emulate a semaphore by creating a counter and then establishing a mutual exclusion region around the counter. However, waiting for a resource such as above, requires a two-level mutex and is not quite so elegant as using the semaphore.