Concurrency Safety · 18 min · free with an account

Deadlock Avoidance

Lesson preview · about 30%

Keep a global lock order and short critical sections.

Core idea

Rust prevents data races, not deadlocks.

Start with the idea

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.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Concurrency & Async