The deadlock
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.
Each thread now asks for its second lock, and another thread holds it. T1 waits for T2, T2 for T3, T3 for T1. A thread asleep in lock() cannot release anything, so none of them ever wakes. This is deadlock.
Detection
So a detector outside the threads checks. It runs every so often, or when a lock has been waited on too long. It builds the wait-for graph: each waiting thread points to the thread holding the lock it wants.
Now it follows the arrows from T1: T1 waits for T2, T2 for T3, T3 for T1. It is back where it started, so there is a cycle. When each lock has only one copy, a cycle means deadlock.
If a resource has several copies, a cycle is not enough proof. The detector asks instead: with the free copies, can some thread finish? It pretends that thread returns what it holds, and repeats. Threads that never finish are deadlocked.
Recovery
To break the cycle, one thread must lose. The detector picks the cheapest to undo: least work done, fewest locks held or lowest priority. In this example T3 has done 1 second of work; T1 and T2 have done 5 and 4.
T3 is aborted: killed, or rolled back to a saved checkpoint so its half-done changes are undone. Either way it lets go of lock C. Its arrows vanish and the cycle is broken.
Lock C is free, so T2, which was waiting for it, gets it. Holding B and C, T2 does its work, finishes and releases both locks.
B is free, so T1 gets it and finishes too. T3 starts again from the beginning. Its lost work is the price of recovery, and if the same timing happens again, it can deadlock again.
In practice
Linux does this for file locks. If an fcntl F_SETLKW request would make processes wait in a circle, the kernel fails one request with EDEADLK. That process is the victim: it gives up its own lock and the other goes ahead.
Detection lets deadlock happen, then finds it: build the wait-for graph and look for a cycle. Recovery breaks the cycle by aborting or rolling back a victim. It suits rare deadlocks; a fixed lock order prevents them more simply.
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.