LightMySky

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.

No account needed. Progress saves in this browser.

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.

Try it together

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.

Good to know

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

Print a worksheetA4 with an answer key page for grown-ups. No screen, no internet.

Where it sits

Then practise

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.

Spotted a problem on this page? Tell us
Deadlock and the Four Conditions · Computing, ages 20 to 22 · LightMySky