The Plain Picture#
Two cooks need both the knife and the cutting board.
Cook 1 grabs the knife, then reaches for the board.
Cook 2 grabs the board, then reaches for the knife.
Each waits for the other to let go. Neither ever will. They stand there forever.
The Real Name#
A deadlock is when two or more threads each hold a lock and wait for a lock another one holds, so none can ever continue.
Under the Hood#
Thread 1 Thread 2 holds Lock A holds Lock B waits Lock B ◀──── cycle ────▶ waits Lock A
A deadlock needs all four of these conditions (the Coffman conditions):
Mutual exclusion — a lock can be held by only one thread.
Hold and wait — a thread holds one lock while waiting for another.
No preemption — nobody can force a lock away from a thread.
Circular wait — there's a cycle of threads each waiting on the next.
Break any one and deadlock is impossible. The practical fixes:
Always take locks in the same global order. If everyone takes A before B, the cycle can't form. This is the standard answer. (Example: when transferring money between two accounts, always lock the account with the smaller ID first.)
Use timeouts — try to get the lock for 100 ms; if you can't, release everything and retry.
Hold fewer locks — redesign so each operation needs only one.
Databases detect deadlocks automatically: they notice the cycle and cancel one transaction, which then fails with a "deadlock detected" error that your code should retry (Transactions and Isolation (coming soon)).
Related: a livelock is when threads keep reacting to each other and retrying but make no progress (two people in a corridor both stepping aside the same way, again and again). Starvation is when one thread never gets a turn because others always win.
Check yourself
3 questionsDefine deadlock in one sentence.
Show answerHide answer
Threads each holding a resource while waiting for one another's, so none can ever proceed.
Name the four conditions needed for a deadlock.
Show answerHide answer
Mutual exclusion, hold and wait, no preemption, circular wait.
What's the most common practical way to prevent deadlocks?
Show answerHide answer
Always acquire locks in the same agreed order.