What is a deadlock, and what are the four necessary conditions for it?
EasyConceptDeadlocks
Answer
A deadlock is a situation in which a set of processes are all blocked, each waiting for a resource that another process in the set is holding, so none of them can ever continue. It can happen only if all four Coffman conditions hold at the same time:
- Mutual exclusion: a resource can be used by only one process at a time, such as a printer or a lock.
- Hold and wait: a process holds at least one resource while waiting for another.
- No preemption: a resource cannot be taken away; the process holding it must release it voluntarily.
- Circular wait: there is a cycle P1 → P2 → … → Pn → P1 in which each process waits for a resource held by the next.
Breaking any one of these conditions makes deadlock impossible.
Example:
Thread A: lock(L1); lock(L2);
Thread B: lock(L2); lock(L1);
If A gets L1 and B gets L2 before either takes its second lock, A waits for L2 and B waits for L1 forever, and all four conditions hold. A real-world picture is four cars at a crossroads, each waiting for the car on its right to move first.