TryBugHunt
rustAsync race conditionHard

Clone Arc Mutex inside thread spawning loop

BugFind the bug and fix the code

What it should do

Increment counter across threads and return total. Example: increment_shared_counter(3) -> 3

What happens instead

Compiler error: use of moved value in closure in loop

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

fn increment_shared_counter(count: usize) -> i32 {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];
    for _ in 0..count {
        // Moving counter directly without Arc::clone moves ownership in first iteration
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        });
        handles.push(handle);
    }
    for h in handles { h.join().unwrap(); }
    let val = *counter.lock().unwrap();
    val
}

fn main() {
    println!("{}", increment_shared_counter(3));
}

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: The move closure moves counter into the spawned thread. In subsequent loop iterations, counter has already been moved, resulting in a compilation error.

The fix: Create a clone of the Arc before spawning each thread: let counter_clone = Arc::clone(&counter); and move that clone into the closure.

Remember: When sharing an Arc across multiple spawned threads in a loop, always clone the Arc for each thread.

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/0ff35384-fdb5-42c4-b3d4-fd72cf3d181f" title="Debugging challenge: Clone Arc Mutex inside thread spawning loop" 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/0ff35384-fdb5-42c4-b3d4-fd72cf3d181f">TryBugHunt</a></p>