How to Use Arc<Mutex<T>> for Thread-Safe Mutable State

Use Arc::new(Mutex::new(value)) to safely share and mutate data across multiple threads in Rust.

Wrap your data in Arc::new(Mutex::new(value)) to share mutable state safely across threads. Arc allows multiple threads to own the data, while Mutex ensures only one thread modifies it at a time.

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

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

    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        });
        handles.push(handle);
    }

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

    println!("Result: {}", *counter.lock().unwrap());
}