How to Share State Between Threads Without a Mutex (Atomics)

Use AtomicUsize with Arc to share and update integer state between threads safely without a Mutex.

Use std::sync::atomic::AtomicUsize (or other atomic types) with std::sync::Arc to share mutable state between threads without a Mutex. Atomics provide lock-free, thread-safe operations for simple types like integers.

use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread;

fn main() {
    let counter = Arc::new(AtomicUsize::new(0));
    let mut handles = vec![];

    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            counter.fetch_add(1, Ordering::SeqCst);
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Result: {}", counter.load(Ordering::SeqCst));
}