Rust

Arc<Mutex<T>> — Shared Mutable State

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Share mutable data across threads: `Arc` for the shared ownership, `Mutex` for the synchronized access. Lock with `.lock().unwrap()`; the guard drops the lock on scope exit.
Rust
Raw
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0u64));

    let mut handles = vec![];
    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        handles.push(thread::spawn(move || {
            for _ in 0..1_000 {
                let mut n = counter.lock().unwrap();
                *n += 1;
                // lock is released when `n` (the guard) goes out of scope
            }
        }));
    }
    for h in handles { h.join().unwrap(); }

    println!("final: {}", *counter.lock().unwrap());     // 10000

    // For simple counters, prefer AtomicU64 — lock-free and faster.
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.