Concurrency Safety · 16 min · free lesson

Mutex Poisoning

Notice a panic that may leave state inconsistent.

Core idea

A standard Mutex becomes poisoned when a holder panics.

A panic while holding a mutex marks its state as needing review before reuse.
Poisoning warns that an invariant may be incomplete.

Understand it

A standard Mutex becomes poisoned when a holder panics. Recovery is possible, but code must decide whether the protected invariant is still trustworthy instead of blindly ignoring the signal.

A standard-library Mutex becomes poisoned if a thread panics while holding its guard. A subsequent lock() returns a PoisonError rather than silently claiming the protected state is sound. The bytes are still there, and the error can give access to the guard, but the application must decide whether its invariant survived. Poisoning is a warning about a possible inconsistency, not proof that the data is corrupt.

Imagine a bank ledger with two fields updated under one lock. If a panic occurs after subtracting from one field but before adding to the other, a future reader must not pretend the transfer completed. Recover only after checking or rebuilding the invariant. A cache whose entries are independently replaceable might be safe to clear and rebuild. A process-wide critical invariant may justify failing the operation instead. The right choice comes from the meaning of the state, not from a universal unwrap() habit.

Write a test in which a worker acquires a mutex and deliberately panics. Join that worker, then inspect the result of the next lock(). Separate the panic returned by join() from the poison returned by lock(): they are two observable events. Add a recovery branch that validates the stored data before clearing poison or continuing. Avoid putting fallible, unrelated work inside a critical section so the chance of leaving a half-updated invariant is smaller. Different mutex implementations have different poison semantics, so verify the actual API you use.

Read the code

use std::sync::Mutex;
let value = Mutex::new(7);
match value.lock() {
    Ok(guard) => println!("{guard}"),
    Err(poisoned) => {
        println!("{}", *poisoned.into_inner());
    }
}

lock returns Err after a holder panicked, and into_inner still gives access to the guard.

Practice starter

use std::sync::{Arc, Mutex};
use std::thread;

let value = Arc::new(Mutex::new(7));
let shared = Arc::clone(&value);
let result = thread::spawn(move || {
    let _guard = shared.lock().unwrap();
    panic!("worker failed");
}).join();
println!("{}", result.is_err());
println!("{}", value.lock().is_err());

Practise this code in Playground ↗

Try it

Predict both printed lines. Then replace the last is_err() with a match that recovers the value through into_inner and checks it before trusting it.

What success looks like: You can separate the panic returned by join from the poison returned by lock, and say when recovery is justified.

Check your understanding

What does poisoning report?

Reveal the answer
  1. A thread panicked while holding the lock
  2. The lock is slow
  3. The value moved

lock returns Err because a thread panicked while holding the guard. The value is still there, but its invariant may be incomplete.

Go deeper

Common misconception: “A poisoned Mutex means the data is corrupted and can no longer be read.”

Poisoning only reports that a holder panicked. The value is still reachable through into_inner, so your code decides whether its invariant survived.

  1. Try the lock: value.lock() returns a Result. No thread has panicked in this example, so it is Ok(guard) and the first arm prints 7.
  2. Read the other arm: Err(poisoned) holds a PoisonError, and it is reached only if a thread panicked while holding the guard.
  3. Decide on recovery: poisoned.into_inner() hands back the guard, which gives the data but no proof that its invariant survived.

Transfer challenge: Model a two-field ledger under one Mutex, panic between the two updates, and write the check that decides whether the next reader may trust it.

Connections

  • Scoped Threads: Borrow local data while threads are guaranteed to join
  • Atomic State: Update one shared value without a lock
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: Mutex Poisoning (courseId "concurrency", lessonId "mutex-poisoning")
Link: https://crabrix.com/learn/concurrency/mutex-poisoning/
Goal: A standard Mutex becomes poisoned when a holder panics.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=concurrency/mutex-poisoning) 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.