1g = waits_for()2loop = find_cycle(g)3abort(cheapest(loop))DETECTORT1T2T3T2 · 4 sBCT1 · 5 sT3 · 1 sAABCT2T3T1
Back: the detector, its code and the wait-for table it fills inFront: threads T1–T3 and locks A–C; gold arrows = held by, rose arrows = waits forTokens: keys (ownership), requests, the detector's eye walking the cycle, the victim's stop signThree threads and three locks on a ring. Gold arrows: the lock is held by that thread. Rose arrows: the thread waits for that lock. The detector turns the arrows into a wait-for table, follows them round the cycle T1, T2, T3, picks T3 as the victim and aborts it; C goes to T2, then B to T1, and T3 starts again. The wait-for graph is the resource allocation graph with the lock nodes removed: an arrow T1 → T2 means T1 waits for a lock that T2 holds. With one copy of each lock, a cycle in it is exactly a deadlock.

The deadlock

  1. Three threads each need two locks: T1 needs A then B, T2 needs B then C, T3 needs C then A. Each grabs its first lock. An arrow from a lock to a thread means that thread holds it.

Detection

Recovery

In practice

What happens

;; step 1/11 · hold
T1:  lock(A); lock(B);  work  unlock both
T2:  lock(B); lock(C);  work  unlock both
T3:  lock(C); lock(A);  work  unlock both

all three run at the same time and get their first lock:
  A held by T1    B held by T2    C held by T3

lock   ->  thread    "held by"

The wait-for graph is the resource allocation graph with the lock nodes removed: an arrow T1 → T2 means T1 waits for a lock that T2 holds. With one copy of each lock, a cycle in it is exactly a deadlock. The work numbers (T1 5 s, T2 4 s, T3 1 s) are made up for the example; real systems weigh work lost, locks held, priority and how often a thread was already the victim.