Concurrency · intermediate

Deadlock

Deadlock is a state in which a set of participants wait indefinitely for resources or events that only another participant in the same waiting set can provide.

Why it matters

Deadlock stops progress without necessarily crashing, so prevention requires reasoning about resource dependencies across code paths rather than inspecting one lock call.

Mental model

How to reason about deadlock

Draw a wait-for graph from each holder to the resource it awaits. A cycle under non-preemptible exclusive ownership is the core danger; consistent ordering prevents that cycle from forming.

Analogy

Two trains each occupy one half of a single track and wait for the other half to clear; neither can advance unless one can back out or be redirected.

Examples

See the boundary, not just the happy path

Worked example · Opposite lock order

A holds X, waits for Y; B holds Y, waits for X

The two wait edges form a cycle, so neither participant can reach the release that the other needs.

Worked example · Prevent with global order

every path acquires X before Y

If no path may hold Y while requesting X, the circular wait between those resources cannot form.

Useful contrast · Livelock

both participants repeatedly release and retry but never advance

Livelocked participants remain active and change state; deadlocked participants are waiting without a possible internal progression.

Common mistakes

Misconceptions to remove early

Labeling any slow lock as deadlock

Contention eventually resolves when a holder releases. Deadlock requires a dependency cycle or equivalent condition that prevents progress indefinitely.

Fixing it with a sleep

Timing changes do not remove the dependency cycle. Enforce ordering, avoid hold-and-wait, allow preemption or timeout, or redesign ownership.

Quick check

Can you predict the result?

1. Which rule directly prevents circular wait among a known set of locks?
  • Acquire those locks in one consistent global order
  • Sleep briefly before every acquisition
  • Give every lock a different variable name
Answer: Acquire those locks in one consistent global order
2. How does livelock differ from deadlock?
Answer: Livelocked participants keep reacting and changing state without progress; deadlocked participants wait with no progress path.

Keep building

Authoritative references

Make the idea retrievable.

Study this concept with spaced repetition, next to the commands where you use it.

Get Terminaster