Intermediatecomparison
What is the difference between a mutex and a semaphore?
ReportedSource: GeeksforGeeks interview experience: Microsoft SDE-I, 1+ year
Quick answer
Mutex: ownership-based lock, one thread in the critical section, unlocked by its owner. Semaphore: counter for N resources or cross-thread signalling, any thread can signal.
Mutex (mutual exclusion lock).
- Protects a critical section so only one thread runs it at a time.
- Has ownership: the thread that locked it must unlock it.
- Typical support for priority inheritance (avoids priority inversion) and recursive variants.
Semaphore.
- An integer counter with
wait/P(decrement, block at zero) andsignal/V(increment, wake a waiter). - Counting semaphore limits concurrent access to N identical resources, e.g. a pool of 5 database connections.
- Binary semaphore (0/1) looks like a mutex but has no ownership: any thread may signal. That makes it suitable for signalling between threads ("data is ready"), not just locking.
Example. Producer-consumer with a bounded buffer: a mutex protects the buffer, semaphore empty counts free slots and full counts filled slots.
One-line rule. Use a mutex to protect shared data; use a semaphore to count resources or to signal events.