Deadlock
A deadlock occurs when two or more threads each hold a resource the other needs, so none can ever proceed. The classic case is thread A holding lock one and waiting for lock two, while thread B holds lock two and waits for lock one.
Deadlock requires all four Coffman conditions at once:
- Mutual exclusion a resource is held by only one thread.
- Hold and wait a thread holds one resource while waiting for another.
- No preemption a resource cannot be forcibly taken away.
- Circular wait a closed chain of threads each waits on the next.
Break any one condition and deadlock becomes impossible. The most common fix is to impose a global lock ordering so every thread acquires locks in the same sequence, destroying the circular wait.
Other tactics include lock timeouts, trylock with backoff, and reducing the number of locks held at once.
Key idea
Deadlock needs four conditions together; enforcing a consistent lock ordering breaks the circular wait and prevents it.