Synchronization PrimitivesMutexes & LocksMedium⏱️ ~2 min

Mutex vs Binary Semaphore

Key Insight
A semaphore initialized to 1 and a mutex both allow only one thread into the critical section. But they have important conceptual differences.
Mutex vs Binary Semaphore
MUTEXHas owner (strict)Only owner can unlockPriority inheritanceDeadlock detectionBINARY SEMAPHORENo owner (flexible)Any thread can signalNo priority inheritanceNo deadlock detection

Ownership Matters

With a mutex, only the thread that acquired the lock can release it. The system knows who owns each mutex. With a semaphore, any thread can signal any semaphore.

Priority Inheritance

If a low-priority thread holds a mutex that a high-priority thread wants, the low-priority thread temporarily inherits the high priority. This prevents priority inversion. Semaphores cannot do this because they do not track ownership.

When To Use Which

Mutex: For protecting shared data. Classic critical section pattern.

Semaphore: For signaling between threads. One thread produces, another consumes. No ownership relationship.

Rule: Use mutex for mutual exclusion, semaphore for signaling. Do not interchange them.
💡 Key Takeaways
Binary semaphore and mutex both enforce mutual exclusion. Functionally similar for basic use.
Mutex has ownership: the thread that locks must unlock. Catches accidental unlock by wrong thread.
Semaphore has no ownership: any thread can signal. More flexible but less safe.
Recursive mutex allows same thread to lock multiple times without deadlock. Semaphore cannot do this.
For simple critical sections, use whichever your language provides. Know the difference for debugging.
📌 Examples
1Mutex catches bugs: Thread A locks, Thread B tries to unlock, error raised. With semaphore, B could unlock A's section.
2Recursive mutex: function A locks, calls function B which also locks. Same thread, so allowed. Semaphore would deadlock.
← Back to Mutexes & Locks Overview