Question presented to candidate: "What is a deadlock? Show me how two Python threads can deadlock, how you would notice it in a running program, and how you design code so it cannot happen."
What a strong answer should cover:
- A deadlock: a set of threads (or tasks, or processes) each waiting for a resource another one in the set holds, so none can ever proceed; the program hangs without an error.
- The classic case: thread 1 holds lock A and waits for B, thread 2 holds B and waits for A β a cycle in the wait-for graph. The four Coffman conditions: mutual exclusion, hold and wait, no preemption, circular wait.
- Python specifics: a plain
threading.Lockis not re-entrant, so a thread that acquires it twice deadlocks itself;threading.RLockallows the owner to re-acquire. - Prevention: one global lock-acquisition order, holding one lock at a time, small critical sections; detection and recovery with
acquire(timeout=...)andjoin(timeout=...). - Other Python forms:
queue.join()with no consumer, a process whose output pipe fills up while the parent waits, asyncio tasks awaiting each other;faulthandler.dump_tracebackorpy-spy dumpshow where threads are stuck.
Code / implementation expected: Optional β two threads with opposite lock order, and the fix with a consistent order or timeouts.