use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; fn main() { // Arc provides thread-safe shared ownership. // Mutex provides thread-safe mutable access. let counter = Arc::new(Mutex::new(0)); let mut handles = vec![]; for i in 0..10 { let counter_clone = Arc::clone(&counter); // Clone Arc for each thread let handle = thread::spawn(move || { let mut num = counter_clone.lock().unwrap(); // Acquire lock, unwrap to get mutable reference *num += 1; // Mutate the shared data println!("Thread {} incremented counter to {}", i, *num); thread::sleep(Duration::from_millis(10)); // Simulate some work }); handles.push(handle); } for handle in handles { handle.join().unwrap(); // Wait for all threads to complete } // After all threads have finished, access the final value println!("Final counter value: {}", *counter.lock().unwrap()); }