Concurrency in Depth · 16 min · free with an account

Deadlocks

Lesson preview · about 30%

Rust prevents data races, not deadlocks.

Core idea

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

Start with the idea

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, will 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.

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 Rust Interview Prep