Unit content
Mutual exclusion, locks and deadlock
When concurrent tasks share mutable state, some groups of operations must behave as one protected critical section.
Mutual exclusion
A mutex allows at most one task at a time to hold the lock protecting a resource or invariant.
lock
read and modify shared state
unlock
The lock must protect the whole relationship that must remain consistent, not merely one variable in isolation.
Waiting instead of racing
If another task already owns the lock, the contender must wait or fail to acquire it according to the synchronization primitive. Correct exclusion converts an unsafe interleaving into an explicit ordering.
Deadlock
Locks can create a new failure: tasks can wait forever in a cycle.
A holds X, waits for Y
B holds Y, waits for X
Consistent lock ordering, avoiding unnecessary lock nesting and reducing shared mutable state help prevent such cycles.
Synchronization is a correctness mechanism with costs: contention can serialize work, and poorly structured locking can harm both liveness and performance.