Prevent Lock Cycles and Shut Down Cooperatively
Core idea
Deadlock can occur when workers hold resources while waiting for each other in a cycle. A consistent global order for acquiring multiple locks prevents that kind of lock cycle. Shutdown should stop accepting work, signal workers, allow cleanup and join them. A timeout detects lack of progress; it does not repair a deadlock.
from threading import Thread, Lockfirst, second = Lock(), Lock()results = []def work(n): with first: with second: results.append(n)workers = [Thread(target=work, args=(n,)) for n in (1,2)]for t in workers: t.start()for t in workers: t.join()print(sorted(results))Neither worker can hold second while waiting to acquire first.
Expected output:
[1, 2]Stop a waiting worker
from threading import Thread, Eventstop = Event()ready = Event()log = []def worker(): try: ready.set() stop.wait() finally: log.append('closed')t = Thread(target=worker)t.start()ready.wait()stop.set()t.join()print(log)The signal lets the worker exit its wait and run cleanup before join returns.
Expected output:
['closed']Common mistake
Never demonstrate a real unbounded deadlock in a learner runner. Avoid joining a worker while holding a lock it needs. Thread.join(timeout) returning does not mean the worker ended; check is_alive.
Practice
Draw a wait-for cycle for workers acquiring A then B and B then A. Rewrite both to acquire A then B and describe the shutdown sequence.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Deadlocks and shutdown
Check your understanding of deadlocks and shutdown.
What is printed?
from threading import Locka=Lock(); b=Lock()with a: with b: print(a.locked(), b.locked())print(a.locked(),b.locked())What is printed?
from threading import Eventstop=Event(); stop.set()print(stop.is_set())Which practice prevents opposite-order lock cycles?
What should follow join(timeout) if termination matters?