Skip to content
← Dist
rustarc_share.rsrustconcurrencyarc

Arc for shared owned data

Share read-mostly state across threads with Arc — and mutate behind a Mutex when needed.

Arc is for shared ownership. Pair with Mutex (or RwLock) when writers exist; skip the lock for immutable snapshots.

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

#[derive(Debug, Default)]
struct Metrics {
    hits: u64,
    misses: u64,
}

fn main() {
    let metrics = Arc::new(Mutex::new(Metrics::default()));
    let label = Arc::new(String::from("edge-cache"));

    let mut handles = Vec::new();
    for i in 0..4 {
        let metrics = Arc::clone(&metrics);
        let label = Arc::clone(&label);
        handles.push(thread::spawn(move || {
            let mut m = metrics.lock().expect("metrics lock");
            if i % 2 == 0 {
                m.hits += 1;
            } else {
                m.misses += 1;
            }
            println!("{label}: worker {i} updated {:?}", *m);
        }));
    }

    for h in handles {
        h.join().expect("worker");
    }

    let final_metrics = metrics.lock().expect("metrics lock");
    println!("done: hits={} misses={}", final_metrics.hits, final_metrics.misses);
}