Mutex vs Semaphore

Why These Two Are Frequently Confused

A mutex and a binary semaphore (covered in the previous note) can look nearly identical in basic usage - both restrict access to a resource to essentially "one at a time." The real difference lies in ownership rules and intended purpose, not just their basic mechanics.

Ownership: The Core Distinguishing Concept

A mutex has a strict ownership rule: only the specific thread that locked it is allowed to unlock it. A semaphore has no such ownership concept at all - any thread can call signal() on a semaphore, regardless of whether that same thread ever called wait() on it.

Mutex:      Thread A locks it -> only Thread A is allowed to unlock it
Semaphore:  Thread A calls wait() -> Thread B is allowed to call signal() on the same semaphore

Different Intended Purposes

MutexSemaphore
PurposeLocking mechanism for mutual exclusionGeneral signaling and counting mechanism
Typical valueLocked / unlocked (conceptually binary)Can count multiple available resource units
Who can release itOnly the thread that acquired itAny thread

Why This Ownership Difference Is More Than Just a Technicality

A mutex's ownership rule lets some systems detect misuse (like a thread trying to unlock a lock it never actually held) and can enable features like priority inheritance to help prevent certain scheduling problems. A semaphore's lack of ownership makes it more flexible for signaling between threads - for instance, one thread producing data and calling signal() for a completely different thread to consume it, a pattern explored directly in the producer-consumer problem covered in the next note.

A Simple Rule of Thumb for Choosing Between Them

Use a mutex specifically for protecting a critical section that one thread locks and later unlocks itself. Use a semaphore when the actual need is signaling between different threads, or tracking a count of multiple available resource instances - genuinely different problems, even when the basic underlying mechanics can look similar at first glance.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.