A deadlock occurs when two or more threads are blocked forever, each waiting for the other to release a resource.
Thread A: Thread B:
Lock(resource1) Lock(resource2)
... ...
Lock(resource2) ← waits Lock(resource1) ← waits
... ...
Unlock(resource2) Unlock(resource1)
Unlock(resource1) Unlock(resource2)
Both threads wait forever.
Deadlock requires all four to be true:
| Condition | Description |
|---|---|
| Mutual Exclusion | Resource can only be held by one thread |
| Hold and Wait | Thread holds resource while waiting for another |
| No Preemption | Resources cannot be forcibly taken |
| Circular Wait | Circular chain of threads waiting |
Break any one condition to prevent deadlock.
| Strategy | How |
|---|---|
| Lock ordering | Always acquire locks in the same order |
| Lock timeout | Give up if lock not acquired in time |
| Try-lock | Non-blocking attempt, back off if fails |
| Single lock | Use one coarse-grained lock |
| Lock-free structures | Avoid locks entirely |
Symptoms:
Tools:
SIGQUIT to dump goroutine stacks