MiddleDebuggingOccasionalNot answered yet
Why can these two locks deadlock?
Two threads run t1 and t2 concurrently and the program sometimes hangs forever.
import threading
a = threading.Lock(); b = threading.Lock()
def t1():
with a:
with b: ...
def t2():
with b:
with a: ...
Find and fix the bug.
Lock-ordering inversion: t1 takes a then b, t2 takes b then a. If each acquires its first lock at once, neither can get the second → deadlock. Fix: acquire locks in a single consistent global order everywhere, or use a timeout (lock.acquire(timeout=...)).
- ✗Believing short critical sections cannot deadlock
- ✗Confusing this with a non-reentrant single-lock re-acquire
- ✗Blaming the GIL rather than the inverted lock order
- →Why does a single consistent global lock ordering prevent deadlock?
- →How does acquiring with a timeout let a thread recover from a potential deadlock?