multithreadingSemaphores & Mutexes


Semaphores & Mutexes are concurrency controls used to synchronize multiple thread access to shared resources.



Here's a brilliant explanation from this Stackoverflow question:

Think of semaphores as bouncers at a nightclub. There are a dedicated number of people that are allowed in the club at once. If the club is full no one is allowed to enter, but as soon as one person leaves another person might enter.

It's simply a way to limit the number of consumers for a specific resource. For example, to limit the number of simultaneous calls to a database in an application.


A mutex is a semaphore of 1 (i.e. only one thread at a time). Using the nightclub metaphor, think of a mutex in terms of a bathroom stall in the nightclub. Only one occupant allowed at a time.