Concurrency Safety · 18 min · free lesson

Deadlock Avoidance

Keep a global lock order and short critical sections.

Core idea

Rust prevents data races, not deadlocks.

Two inconsistent lock orders form a wait cycle; a shared order breaks it.
Acquire multiple locks in one documented order.

Understand it

Rust prevents data races, not deadlocks. A consistent order for acquiring multiple locks and avoiding calls into unknown code while locked remove common wait cycles.

A deadlock can arise when worker A holds lock X while waiting for Y and worker B holds Y while waiting for X. Both workers may be perfectly data-race-free, yet neither can move. Rust's ownership rules do not decide a global lock order for your program. The simplest prevention is often a consistent acquisition order: if every path takes X before Y, the cycle cannot form from those two locks.

Draw a wait-for graph with one node per task and an arrow when it waits for a resource held by another task. A cycle is the warning sign. Reduce the number of locks held at once, move expensive work outside locked sections, or combine related fields under a single mutex when the data model allows it. try_lock can avoid indefinite waiting in some designs, but a retry loop without backoff can livelock or waste CPU. Timeouts help detection and recovery; they do not automatically make a transfer atomic.

Build two workers that each need two locks. First write the unsafe ordering on paper, then rewrite both workers to acquire locks in the same order. Ask what happens if a callback called while holding X attempts to acquire X again: a non-reentrant mutex may self-deadlock. Avoid invoking unknown callbacks while a guard is alive. When reviewing a codebase, document the lock hierarchy near the shared state, not only in one caller. Tests can expose some schedules; a clear acquisition rule is the stronger argument that a cycle cannot occur.

Read the code

// Every path locks account id in ascending
// order before transferring a balance.
let (first, second) = if a_id < b_id {
    (&a, &b)
} else {
    (&b, &a)
};

Sorting by id gives every transfer the same first lock, so two transfers cannot wait on each other.

Practice starter

use std::sync::Mutex;

static X: Mutex<i32> = Mutex::new(0);
static Y: Mutex<i32> = Mutex::new(0);

fn worker_a() {
    let mut x = X.lock().unwrap();
    let mut y = Y.lock().unwrap();
    *x += 1;
    *y += 1;
}

fn worker_b() {
    let mut x = X.lock().unwrap();
    let mut y = Y.lock().unwrap();
    *y -= 1;
    *x -= 1;
}

Practise this code in Playground ↗

Try it

Swap the two lock lines in worker_b and draw the wait-for graph. Say which schedule hangs, and check that the compiler still accepts the code.

What success looks like: You can point to the cycle in the swapped version and to the lock order that removes it.

Check your understanding

What prevents the wait cycle here?

Reveal the answer
  1. Both workers lock in one order
  2. Running more threads
  3. A mutable borrow

Both workers take X before Y, so neither can hold Y while waiting for X, and that cycle cannot form.

Go deeper

Common misconception: “Rust's ownership rules would reject a program that can deadlock.”

Rust prevents data races, not deadlocks. Code that locks in opposite orders compiles, so a consistent lock order has to come from your design.

  1. Compare the ids: a_id < b_id decides which account comes first, whichever way round the caller passed them.
  2. Take the pair: The if returns a tuple of references, so first always names the lower id and second the higher.
  3. Check the cycle: If every path locks first before second, no two transfers can hold one account while waiting on the other, so that cycle cannot form.

Transfer challenge: Extend the example to lock first and then second and move a balance. Then decide what must happen when a_id == b_id, since both names would reach the same Mutex.

Connections

  • Atomic State: Update one shared value without a lock
  • Pinning Intuition: Promise that a value will not move in memory
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: Deadlock Avoidance (courseId "concurrency", lessonId "deadlock-avoidance")
Link: https://crabrix.com/learn/concurrency/deadlock-avoidance/
Goal: Rust prevents data races, not deadlocks.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=concurrency/deadlock-avoidance) 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.