Deadlock and the Four Conditions
Deadlock needs mutual exclusion, holding while waiting, no preemption, and a cycle of waiting. Removing any one of the four prevents it, which is why a fixed lock ordering is the usual answer in real code.
What a learner can do afterwards
- Draw the wait-for graph of a deadlocked pair of threads and find the cycle
- Break a given deadlock by removing one of the four conditions
- Explain how a global lock ordering prevents the cycle from forming
1 · Read
You already know two threads can share locks. A deadlock needs four things at once: each lock has one holder, each thread holds one lock while asking for another, nobody can take a held lock away, and the waiting forms a cycle.
Thread A holds lock 1 and waits for lock 2. Thread B holds lock 2 and waits for lock 1. Draw an arrow from each waiter to the holder of the lock it wants. The arrows make a cycle, and that cycle is the deadlock.
Remove any one of the four and the deadlock breaks. The usual fix removes the cycle: agree on one order for all locks, such as lock 1 before lock 2, and make every thread follow it. With one order everywhere, a waiting cycle cannot form.
When your program freezes with no crash, sketch who holds what and who waits for what. If you find a cycle, pick the lock order that one thread breaks and change it to match the rest.
Deadlock needs all four conditions at once, so one shared lock order everywhere keeps the cycle from forming.
2 · Watch
Take it off screen
Where it sits
8 questions wait behind this lesson, each with its answer explained. Every answer feeds the sky: stars light as they are learned, and dim when it is time to come back.