Concurrency · intermediate
Mutex
A mutex is an ownership-based synchronization primitive that permits at most one execution context at a time to hold it and enter the protected critical section.
Why it matters
A correctly scoped mutex serializes conflicting access to shared invariants, while poor scope or ordering can create contention, deadlock, or unprotected gaps.
Mental model
How to reason about mutex
The mutex guards an invariant, not merely a line. Every path that reads or changes the protected state follows the same lock protocol, and the owner releases it promptly.
Analogy
A room has one physical key. Whoever holds it has exclusive access, must finish the protected task, and returns the key for the next entrant.
Examples
See the boundary, not just the happy path
Worked example · Protect a compound invariant
lock(); remove from queue; update count; unlock()The queue contents and count change together while no other holder can observe or modify the intermediate state.
Worked example · Release on every exit
with lock: updateSharedState()A scoped locking construct releases the mutex even when the body returns or throws, avoiding a permanently held lock.
Avoid · Lock only writers
writer locks; reader accesses mutable structure unlockedA reader can still race with mutation or observe a broken invariant. All conflicting access must follow the protocol.
Common mistakes
Misconceptions to remove early
Holding a lock across slow external work
Network or disk waits extend contention and can create dependency cycles. Capture needed state, release when safe, then perform slow work outside.
Assuming fairness
Many mutex APIs do not guarantee first-waiter-first acquisition. A correct design cannot depend on an undocumented scheduling order.
Quick check
Can you predict the result?
1. What should determine which state a mutex protects?
- • The complete shared invariant and every conflicting access path
- • Only the shortest source line
- • Whichever variable was declared first
2. Why are scoped lock constructs safer than manual unlock calls?
Keep building