Mutex vs Semaphore: Differences Explained
A mutex protects a critical section so that only one thread at a time can use a shared resource, and the thread that locked it must be the one that unlocks it. A semaphore is a counter: it controls how many threads can use a limited resource, and it can also be used to signal events from one thread to another. A mutex is about ownership and exclusion; a semaphore is about counting and signaling.
| Aspect | Mutex | Semaphore |
|---|---|---|
| Purpose | Mutual exclusion: one thread at a time in a critical section | Counting: limit access to a pool of N resources, or signal events between threads |
| Value | Locked or unlocked (binary) | A non-negative integer count (a binary semaphore is the special case of 0 or 1) |
| Ownership | Owned by the thread that locked it, and that thread should unlock it | No owner: any thread can post or signal |
| Operations | Lock and unlock | Wait (P, decrement) and post (V, increment) |
| Signaling between threads | Not intended for it | Yes: for example a producer signaling a consumer |
| Priority inversion | Often avoided with priority inheritance | Usually not supported |
| Typical uses | Protecting a shared data structure such as a list or a counter | Limiting a connection pool, bounded producer-consumer buffers, signaling from an interrupt handler to a task |
| Common pitfalls | Deadlock from inconsistent lock order, or forgetting to unlock | Lost signals and deadlock when counts do not match |
Figures are typical orders of magnitude and vary by process generation and product.