TryBugHunt
rustAsync race conditionHard

Poisoned mutex lock propagation after panic

BugFind the bug and fix the code

What it should do

Safely read mutex value even if previously poisoned. Example: recover_poisoned_mutex(10) -> 10

What happens instead

panicked at 'called `Result::unwrap()` on an `Err` value: PoisonError'

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

fn recover_poisoned_mutex(val: i32) -> i32 {
    let lock = Arc::new(Mutex::new(val));
    let c = Arc::clone(&lock);
    let _ = thread::spawn(move || {
        let _guard = c.lock().unwrap();
        panic!("worker panicked while holding lock");
    }).join();

    // Calling .unwrap() on poisoned lock panics with PoisonError
    *lock.lock().unwrap()
}

fn main() {
    println!("{}", recover_poisoned_mutex(10));
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the async and race conditions pattern

Shared state behind the wrong lock, a lock held too long, or a channel that hangs.

What you'll practise

A hard Rust debugging exercise about async and race conditions: shared state behind the wrong lock, a lock held too long, or a channel that hangs.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

What went wrong: If a thread panics while holding a Mutex lock, the Mutex becomes poisoned. Future calls to lock() return Err(PoisonError), so calling .unwrap() triggers a panic.

The fix: Handle the PoisonError using match or unwrap_or_else and call poisoned.into_inner() to recover the underlying data.

Remember: Mutex::lock() returns Result to notify callers that a prior lock holder panicked. Use into_inner() to recover data from poisoned locks.

The pattern behind it: async and race conditions.

More async and race conditions to practise

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/3fbaae19-ddb8-4457-9d9a-842ae6bdf157" title="Debugging challenge: Poisoned mutex lock propagation after panic" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/3fbaae19-ddb8-4457-9d9a-842ae6bdf157">TryBugHunt</a></p>