Operating systems · core
Deadlock and its four conditions
A deadlock is a set of processes that wait for each other forever. It needs four conditions together, so breaking one prevents it.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Deadlock: each process in a set waits for a resource held by another in the set, so none can continue.
- Four Coffman conditions: mutual exclusion, hold and wait, no preemption, circular wait. All four must hold.
- Example: A holds the pen and waits for the notebook; B holds the notebook and waits for the pen.
- Prevention: break one condition. In code the usual way is to always take locks in the same global order, which breaks circular wait.
- Other ways: ask for all resources at once (breaks hold and wait), use a lock with a timeout, or let the OS take a resource away (preemption).
- A hang with zero CPU use suggests threads waiting on each other, not an endless loop. Take a thread dump (jstack for Java, py-spy dump for Python, gdb with thread apply all bt for C) to see who holds which lock.
- Example bug: thread 1 locks students then backup; thread 2 locks backup then students. Fix: both lock students first, then backup.
- Deadlock is not starvation. In starvation one process waits a long time but others keep running.
The red pen
Common traps: mistake → fix
Mistake: Two or three conditions are enough for deadlock
Fix: all four must hold.
Mistake: Restart the system is a fix
Fix: it only clears it; the lock order bug returns.
Mistake: Add sleeps to avoid the hang
Fix: it only changes the timing.
Mistake: A slow program is a deadlocked one
Fix: a deadlocked program makes no progress at all.
Easy to hard
Questions interviewers ask, easy to hard
- What is deadlock? Name the four conditions.
- How do you prevent deadlock in code?
- A program hangs with 0% CPU. How do you find out why?
- What is the difference between deadlock and starvation?
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.