Synchronization Primitives • Mutexes & LocksEasy⏱️ ~2 min
What is a Mutex?
Definition
A mutex (mutual exclusion) is like a token that passes from one thread to another, allowing one thread at a time to proceed. Only the thread holding the token can enter the critical section.
The Key Difference From Semaphores
A mutex has an owner. The thread that locks the mutex must be the one to unlock it. This constraint prevents accidental releases and enables useful features like priority inheritance.
Mutex Ownership Model
The Two Operations
lock(): Acquire the mutex. If already held by another thread, block until released. If you already own it (in most implementations), either block forever (deadlock) or increment a counter (recursive mutex).
unlock(): Release the mutex. Must be called by the owner. Wakes one waiting thread if any.
Think Of It Like A Bathroom Door Lock
When you enter, you lock the door. When you leave, you unlock it. You cannot unlock from outside, only the person inside can unlock. If someone is inside, others wait in line.
Key Point: Mutex = mutual exclusion with ownership. The owner model prevents accidental unlocks and enables deadlock detection.
💡 Key Takeaways
✓A mutex ensures only one thread executes the critical section at a time. This is mutual exclusion.
✓Implemented as a semaphore with initial value 1. wait() to enter, signal() to exit.
✓The token metaphor: thread must get the mutex before proceeding, release it when done.
✓The room metaphor: thread locks the door to enter, unlocks to let others in.
✓Mutex provides exclusive access to shared resources like variables, files, or data structures.
📌 Examples
1Protecting counter: mutex.wait(); count = count + 1; mutex.signal();
2Protecting list insert: mutex.wait(); list.append(item); mutex.signal();