🧠
Mechanism Depth - How It Works
💡 This is what product companies expect for a solid conceptual understanding.
Intuition
Mutex enforces exclusive ownership with blocking and unlocking semantics; semaphore manages a resource count with wait and signal operations.
Explanation
A mutex is a locking mechanism that guarantees mutual exclusion by allowing only the thread that locked it to unlock it, preventing accidental release by others. It typically blocks other threads attempting to acquire it until it is released. Semaphores maintain an internal counter representing available resources. When a thread performs a wait (P) operation, the counter decrements; if the counter is zero, the thread blocks. When a thread signals (V), the counter increments, potentially waking blocked threads. Counting semaphores allow multiple concurrent accesses up to the count, while binary semaphores restrict access to one but do not enforce ownership, which can lead to subtle bugs if misused. Mutexes are preferred when strict ownership and exclusive access are required, such as protecting critical sections. Semaphores are ideal for managing pools of identical resources or signaling between threads.
Memory Hook
💡 Imagine a mutex as a bathroom key that only the person inside can return, while a semaphore is like a parking lot gate that counts available spots and lets cars in or out accordingly.
Illustrative Code
import threading
class Mutex:
def __init__(self):
self.lock = threading.Lock()
self.owner = None
def acquire(self):
self.lock.acquire()
self.owner = threading.get_ident()
def release(self):
if self.owner != threading.get_ident():
raise RuntimeError('Mutex released by non-owner')
self.owner = None
self.lock.release()
class Semaphore:
def __init__(self, count):
self.sem = threading.Semaphore(count)
def wait(self):
self.sem.acquire()
def signal(self):
self.sem.release()
# Usage example
mutex = Mutex()
semaphore = Semaphore(3)
# Mutex usage
mutex.acquire()
# critical section
mutex.release()
# Semaphore usage
semaphore.wait()
# critical section
semaphore.signal()
Interview Questions
❓ What happens if a thread tries to release a mutex it does not own?
- This is undefined behavior or error in most implementations
- Mutex ownership prevents this to avoid race conditions
- Semaphore does not enforce ownership, so this can happen
❓ When would you prefer a semaphore over a mutex?
- When multiple identical resources are available
- When you need to allow limited concurrent access
- When signaling between threads without exclusive locking