π Python Systems Engineering β Deadlocks π
Posted on: November 26, 2026
Description:
A dashboard says both workers are alive. The queue still isnβt moving. Each worker needs locks A and B to finish its job. To find the stall, take a snapshot of who holds each lock and who needs it next.
Follow the wait
| Worker | Holds | Needs next | Must wait for |
|---|---|---|---|
| P1 | A | B | P2 |
| P2 | B | A | P1 |
Read the last column as arrows between workers: P1 β P2 β P1. P1 can release A after it acquires B and finishes. P2 can release B after it acquires A and finishes. With indefinitely blocking calls and no outside intervention, neither reaches its release. That circular wait is the deadlock.
Reproduce the conflict in Python
The companion script starts two real processes with shared multiprocessing.Lock objects. A barrier makes both acquire their first lock before either probes the second. Both keep their first locks until both probes finish. This gives us a reproducible snapshot without relying on a well-timed sleep.
# Inside each worker, with its first lock already held
gate.wait(timeout=8)
available = locks[second].acquire(block=False)
if available:
locks[second].release()
gate.wait(timeout=8)
Both probes returned False. We then let each worker try its second lock with a one-second timeout. In the recorded run P1 timed out, left its cleanup block and released A. P2 acquired A and completed. On another run the roles can reverse, or both attempts can expire. A slow owner can also cause a timeout. The ownership cycle is what identifies the problem here. Python multiprocessing locks
Prevent the cycle with one rule
Assign a common rank to the locks. Here the names already supply one: A before B. Apply the ranking before acquiring either lock, regardless of which order the caller requested.
def run_job(locks, requested, work):
first, second = sorted(requested) # Two distinct lock names
with locks[first]:
with locks[second]:
work()
Suppose P1 gets A first. P2 waits for A while holding nothing, leaving B available to P1. When P1 finishes, P2 can proceed. The bounded version in the notebook ran both jobs to completion. Either worker can go first.
This rule works because a worker holding one lock can request only a higher-ranked lock. A sequence of increasing ranks cannot lead back to its starting point. It matters that every acquisition path follows the same rule, including helpers called while another lock is held.
No comments yet. Be the first to comment!