Shared State with Mutex and RwLock
Updated
October 31, 2026
Shared State with Mutex and RwLock
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..5 {
let counter_clone = Arc::clone(&counter);
handles.push(thread::spawn(move || {
let mut num = counter_clone.lock().unwrap();
*num += 1;
}));
}
for h in handles { h.join().unwrap(); }
println!("Final count: {}", *counter.lock().unwrap());
}