How to Use std

:sync for Synchronization Primitives

Use Arc and Mutex from std::sync to safely share mutable data across threads in Rust.

Use std::sync primitives like Mutex and Arc to safely share mutable state between threads by wrapping data and acquiring locks before access.

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

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());