/ THE IDEA
Imagine a programme that must update two protected records, named A and B. One worker takes A’s lock first, while another takes B’s lock first. If each then waits for the remaining lock without releasing the first, neither can reach the code that releases anything. A global lock order removes this particular cycle. Give every lock a rank, and require every worker to acquire needed locks from smaller rank to larger rank. A waiting chain then goes upward in rank; it cannot loop back down to where it started.
THE FORMAL IDEA
unsafe: A → B and B → A; ordered: A → B for everyone
| A and B name locks, not memory amounts. The arrows mean “hold the first while requesting the second”. | | A wait-for cycle means following these requests eventually leads back to an already waiting worker. Lock ranks are labels used for ordering, not times or priorities. |
|
RUN THE TINY EXAMPLE
Change one thing. Predict what happens.
Worker 1 holds A and requests B. Worker 2 holds B and requests A. Both must wait; completed two-record updates = 0. Change only the acquisition rule: both workers request A before B. Worker 1 obtains both and finishes; worker 2 then obtains both and finishes. Completed updates = 2.
|
The ordered rule makes one worker wait earlier, before it owns the second worker’s needed resource. It does not make the operation simultaneous. It replaces a possible permanent standstill with a sequence that can complete.
/ SO WHAT?
The rule has to be global across the relevant programme. A helper function quietly taking a lower-ranked lock can break the reasoning even if its caller looks correct. That is why documenting ownership and acquisition order can matter more than scattering extra locks around a bug. Timeouts can reveal waiting, but retries still need a safe release and recovery policy.
ONE CAVEAT |
| Lock ordering prevents cycles among locks following that order, not every possible hang. Workers can still wait for lost messages, never-ending calculations or resources outside the scheme, and unfair scheduling can delay a worker indefinitely. |
KEEP THIS
When all nested lock requests move in one agreed direction, that set of locks cannot form a circular wait.
|
NEXT: Why a tiny bead feels a different kind of drag
|