Mutex vs Semaphore
Both a mutex and a semaphore coordinate access to shared resources, but they solve different problems.
A mutex is a mutual exclusion lock. Exactly one thread may hold it at a time. The thread that locks a mutex is normally the one that must unlock it, giving the mutex a concept of ownership.
A semaphore is a counter that permits a fixed number of threads to proceed. A binary semaphore allows one, while a counting semaphore allows several. Any thread may signal a semaphore, so it has no ownership.
- Mutex protects a critical section so only one thread runs it.
- Semaphore limits concurrency, for example allowing five database connections.
- A mutex is best for protecting data. A semaphore is best for managing a pool of identical resources or signaling between threads.
Using a semaphore where a mutex belongs can hide bugs because the ownership guarantee is lost.
Key idea
Use a mutex for exclusive ownership of one critical section; use a semaphore to count and limit access to a pool of resources.