A mutex is a lock that guarantees mutual exclusion — only one thread can hold it and enter the protected critical section at a time. A semaphore generalizes this to allow up to N concurrent holders.
A mutex is a lock that guarantees mutual exclusion — only one thread can hold it and enter the protected critical section at a time. A semaphore generalizes this to allow up to N concurrent holders.
acquire() decrements (blocks at 0), release() increments. A mutex is essentially a semaphore with N=1 but with ownership semantics.lock = threading.Lock()
def transfer(a, b, amt):
with lock: # critical section — one thread at a time
a.balance -= amt
b.balance += amt
# Semaphore: cap concurrent DB connections at 10
sem = threading.Semaphore(10)
def query():
with sem: # up to 10 threads run this concurrently
db.execute(...)
with/RAII/defer so release is automatic even on exceptions.These are the everyday tools for protecting shared state. Mutexes serialize access to prevent races; semaphores throttle a resource pool (connections, permits, rate limits). Choosing the right primitive and keeping critical sections short is the difference between correct-and-fast and correct-but-slow.
A library of IT interview questions with detailed answers — from Junior to Senior.
Donate