What is the difference between a mutex and a semaphore? Is a binary semaphore the same thing as a mutex? Give one situation where you would use each.
Show hints
Ask who is allowed to release it.
Show the explanation
Model answer.
Mutex (mutual-exclusion lock)
- Has two states: locked and unlocked.
- Has the concept of ownership: the thread that locked it is the one expected to unlock it.
- Purpose: protect a critical section so only one thread touches shared data at a time.
- Because the owner is known, implementations can support features such as priority inheritance, recursive locking and error checking when a non-owner tries to unlock.
Semaphore
- An integer counter with two atomic operations:
wait(P / down) decrements and blocks if the value would go below zero;signal(V / up) increments and wakes a waiting thread if there is one. - No ownership: any thread may signal, even one that never waited.
- A counting semaphore initialised to N lets up to N threads use a pool of N identical resources (e.g. N database connections).
- A semaphore initialised to 0 is a clean signalling tool: thread A waits until thread B signals that an event happened.
Is a binary semaphore a mutex? Functionally they can both enforce mutual exclusion, but they are not the same. A binary semaphore can be released by any thread, so it can be used for signalling between threads, while a mutex is meant to be released only by its owner. Ownership is what allows priority inheritance and helps catch bugs.
When to use which
- Mutex: guarding a shared linked list or a bank balance update.
- Counting semaphore: limiting concurrent downloads to 5, or the classic producer–consumer bounded buffer (one semaphore counts empty slots, one counts full slots, plus a mutex for the buffer itself).
Common follow-up: "In producer–consumer, what goes wrong if you acquire the mutex before waiting on the empty-slots semaphore?" The producer may sleep while holding the mutex, so the consumer can never enter to free a slot — a deadlock.
Original UniCircle question. Last reviewed 28 Oct 2026.
