Repair State After Mutex Poisoning Across Threads

Recover an Arc<Mutex<T>> lock after a worker thread panics using PoisonError::into_inner, then inspect and repair the partial mutation safely.

RustResilience

Code

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

#[derive(Debug)]
struct BatchLedger {
    committed: Vec<&'static str>,
    in_flight: Option<&'static str>,
}

fn main() {
    // Silence default panic output so stderr stays clean during recovery demo
    std::panic::set_hook(Box::new(|_| {}));

    let ledger = Arc::new(Mutex::new(BatchLedger {
        committed: vec!["tx-100"],
        in_flight: None,
    }));

    let worker_ref = Arc::clone(&ledger);
    let handle = thread::spawn(move || {
        let mut guard = worker_ref.lock().unwrap();
        guard.in_flight = Some("tx-101");
        panic!("simulated crash mid-commit");
    });

    println!("worker panicked: {}", handle.join().is_err());

    let mut recovered = match ledger.lock() {
        Ok(g) => g,
        Err(poisoned) => {
            println!("mutex poisoned; recovering via PoisonError::into_inner");
            poisoned.into_inner()
        }
    };

    if let Some(aborted) = recovered.in_flight.take() {
        println!("rolled back incomplete job: {aborted}");
    }
    recovered.committed.push("tx-102");
    println!("repaired ledger: {:?}", *recovered);
}

Implementation trace — Repair State After Mutex Poisoning Across Threads

Everything happens inside the function main.

A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

Caveats

  • Every identifier touched originates from core language built-ins without external pulls.

Using it

Execution kicks off via header fn main()

Output lines are prefixed (worker panicked:, rolled back incomplete job:, repaired ledger:), revealing distinct execution milestones visibly inside terminal logs.

Key statements

if let Some(aborted) = recovered.in_flight.take() {
    println!("rolled back incomplete job: {aborted}");
}
Err(poisoned) => {
    println!("mutex poisoned; recovering via PoisonError::into_inner");
    poisoned.into_inner()
}
let mut guard = worker_ref.lock().unwrap();

Interactive Tools for This Topic

FAQ

What does Repair State After Mutex Poisoning Across Threads print when run?
Invoke the file as-is — the `worker panicked:`, `rolled back incomplete job:`, `repaired ledger:` prefixes identify which step printed each line.