Deadlock
A deadlock is a standstill where each participant waits for a resource another participant holds, so nobody can move. In Python it is usually two locks taken in opposite order, or a thread joining itself.
Detailed Explanation
The classic picture is two threads and two locks. Thread 1 holds A and wants B. Thread 2 holds B and wants A. Both acquire calls wait forever. The same shape appears with asyncio.Lock, with a thread waiting on a future that only it can complete, and with join on the current thread.
Four conditions (Coffman) make a deadlock possible: exclusive locks, hold-and-wait, no preemption, and a circular wait. You break the circle. The practical rules: impose a global lock order (always A then B); take multiple locks with a single helper; use acquire(timeout=) and fail instead of waiting forever; prefer a queue so there is only one owner of the mutable state.
Re-entrancy is a private deadlock. Lock is not reentrant. A method that takes the lock and calls another method that takes the same lock will hang in one thread. RLock or a single acquire at the API boundary fixes it.
Joins deadlock too. Thread A joins B, B joins A. A pool whose workers submit work to the same pool and then future.result() can stall if the pool is full (all workers waiting, no worker free to run the nested task). Use a larger pool, a separate pool, or do not block a worker on more work from the same pool.
Asyncio deadlocks look like a freeze without high CPU. A task awaits a future that only a blocked loop can complete. asyncio.Lock held across an await that needs the same lock is the async version of re-entrancy.
Detection: print lock acquisition in debug builds, use faulthandler, dump stacks with sys._current_frames() or threading.enumerate(). Timeouts turn a deadlock into an error you can log.
Code Examples
import threading
a = threading.Lock()
b = threading.Lock()
def ordered() -> None:
# One global order: a then b. Both threads use it.
with a:
with b:
pass# Self-join: this never returns.
# threading.current_thread().join()# Timeout turns a possible deadlock into a boolean.
lock = threading.Lock()
if lock.acquire(timeout=1.0):
try:
pass
finally:
lock.release()
else:
print("could not acquire")Common Gotchas
Opposite lock orders in two functions
it will pass tests until the schedule hits. Sort locks by `id(lock)` if you must take an arbitrary pair.
`Lock` taken twice on one thread
use `RLock` or restructure.
Workers calling `future.result()` on their own pool
keep nested work off that pool or use `timeout`.
The GIL cannot deadlock itself the way two user locks can
user-level cycles are still yours to avoid.