use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; fn main() { // Create a shared counter, protected by a Mutex for exclusive access // and wrapped in an Arc for multiple, thread-safe owners. let counter = Arc::new(Mutex::new(0)); let mut handles = vec![]; for i in 0..5 { let counter_clone = Arc::clone(&counter); let handle = thread::spawn(move || { println!("Thread {} started.", i); thread::sleep(Duration::from_millis(100 * i as u64)); // Simulate work // Acquire a lock on the Mutex. // This blocks until the lock is available. let mut num = counter_clone.lock().unwrap(); *num += 1; // Mutate the shared data println!("Thread {} incremented counter to {}.", i, *num); // The lock is automatically released when `num` goes out of scope // (at the end of this closure or when it's dropped). }); handles.push(handle); } // Wait for all threads to complete for handle in handles { handle.join().unwrap(); } // Access the final value of the counter println!("Final counter value: {}.", *counter.lock().unwrap()); // Demonstrate sharing a more complex data structure let shared_data = Arc::new(Mutex::new(vec!["initial".to_string()])); let data_clone = Arc::clone(&shared_data); let handle_data = thread::spawn(move || { let mut data = data_clone.lock().unwrap(); data.push("modified by thread".to_string()); }); handle_data.join().unwrap(); println!("Final shared data: {:#?}", *shared_data.lock().unwrap()); }