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

Wrap shared data in Mutex<T> and call lock() to safely mutate it across multiple threads.

Use Mutex<T> to wrap shared data and call .lock() to get a mutable reference that blocks other threads until the lock is released.

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

let data = Arc::new(Mutex::new(0));
let mut handles = vec![];

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

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

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