Concurrency in Depth · 16 min · free lesson

Deadlocks

Rust prevents data races, not deadlocks.

Core idea

Data-race freedom is a compile-time guarantee; deadlock freedom is a design one.

Lesson map: two threads locking a and b in opposite orders, above the rule that deadlock freedom is a design guarantee, not a compile-time one.
Two orders, one hang. The types all check out.

Understand it

The borrow checker knows nothing about the order in which you take locks, so two threads taking Mutex A then Mutex B, and B then A, can still hang. The standard answers are a global lock order, holding one lock at a time, using try_lock with a timeout, or removing shared state entirely by moving to channels. Knowing Rust does not solve this is the point of the question.

A deadlock is a cycle of waits. Worker A holds lock X and waits for Y; worker B holds Y and waits for X. Each lock protects data correctly, so Rust's data-race protections do not reject the program. The fix begins with a wait-for graph or a documented lock hierarchy. If every path acquires X before Y, that particular two-lock cycle cannot form. Another design is to avoid holding two locks at once by copying the needed data out or sending a message to an owner task.

Be precise about alternatives. try_lock can fail rather than block, but a tight retry loop can livelock or burn CPU. A timeout detects a long wait but does not make partial state changes atomic. Dropping one lock before taking the next may remove the deadlock while introducing a race in the business invariant; review what must remain consistent. A channel can simplify ownership when work can be expressed as commands rather than shared mutation.

In an interview, start with the cycle and show one concrete break in it. Then describe how you would verify the rule in a larger codebase: document lock order beside the shared state, avoid callbacks while holding locks, and test representative interleavings. Do not promise that stress tests prove deadlock freedom. The convincing part is an invariant that prevents a cycle, supported by tests for the implementation.

Self-deadlock deserves mention: a function can acquire a non-reentrant mutex and call another helper that tries to acquire the same mutex. A global order among two different locks does not prevent that. Document which helpers require a lock to be held and which acquire it themselves, and avoid invoking unknown callbacks under a guard.

Interview follow-up: Would an async mutex remove an opposite-order cycle? Discuss reentrant calls, cancellation and lock scope separately.

Read the code

// thread 1
let _a = a.lock().unwrap();
let _b = b.lock().unwrap();

// thread 2
let _b = b.lock().unwrap();
let _a = a.lock().unwrap();

Two orders, one hang. The types all check out.

Practice starter

// Worker A acquires first, then second.
// Worker B acquires second, then first.
// Both may wait while holding their first lock.

Practise this code in Playground ↗

Try it

Name three ways to remove a deadlock without changing behaviour.

What success looks like: Your answer includes a lock order and one lock-free alternative.

Check your understanding

Which design change directly removes the opposite-lock-order cycle?

Reveal the answer
  1. Use one documented lock order everywhere, or merge state behind one suitable lock.
  2. Replace both mutexes with RwLock while retaining the acquisition order.
  3. Delay the second acquisition by a fixed sleep on each worker.

An ordering rule removes this circular wait if all relevant paths follow it. Sleeps change timing, not the possibility of a cycle.

Go deeper

Common misconception: Replace both mutexes with RwLock while retaining the acquisition order.

RwLock writers still wait for each other, so opposite-order acquisition can form the same cycle. Changing the lock type leaves the order, and the cycle, in place.

  1. Identify the contract: Rust prevents data races, not deadlocks.
  2. Trace the concrete example: Two orders, one hang. The types all check out.
  3. Test the changed constraint: Would an async mutex remove an opposite-order cycle? Discuss reentrant calls, cancellation and lock scope separately.

Transfer challenge: Would an async mutex remove an opposite-order cycle? Discuss reentrant calls, cancellation and lock scope separately.

Connections

  • Atomics and Ordering: Relaxed, Acquire/Release, SeqCst
  • Channels vs Mutex: Moving ownership or sharing it
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Deadlocks (courseId "interview", lessonId "q-deadlock")
Link: https://crabrix.com/learn/interview/q-deadlock/
Goal: Data-race freedom is a compile-time guarantee; deadlock freedom is a design one.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=interview/q-deadlock) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.