Shared State With Arc and Mutex

Share mutable counters across threads with Arc for ownership and Mutex for exclusive access, avoiding data races at compile time.

RustResilience

Code

rustsnippet
23 lines
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0u64));
    let handles: Vec<_> = (0..8)
        .map(|_| {
            let counter = Arc::clone(&counter);
            thread::spawn(move || {
                for _ in 0..1000 {
                    let mut value = counter.lock().expect("mutex poisoned");
                    *value += 1;
                }
            })
        })
        .collect();

    for handle in handles {
        handle.join().expect("thread panicked");
    }
    let total = *counter.lock().expect("mutex poisoned");
    println!("total = {total}");
}

How it works

Shared State With Arc and Mutex comes down to the function main.

Repetition is confined to for _ in 0..1000 — the rest of the file is straight-line.

Putting it to use

Entry signature: fn main()

Running the file prints labeled results such as total = — each operation’s effect is visible in the output.

Core lines

thread::spawn(move || {
for _ in 0..1000 {
let mut value = counter.lock().expect("mutex poisoned");
*value += 1;
}
})

Interactive Tools for This Topic

FAQ

What does Shared State With Arc and Mutex print when run?
No setup needed: run the file and look for labeled lines like `total =` in the output.