use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; fn main() { // Create a shared counter, protected by a Mutex, shared across threads via Arc. let counter = Arc::new(Mutex::new(0)); let mut handles = vec![]; for i in 0..5 { let counter_clone = Arc::clone(&counter); // Increment Arc's reference count let handle = thread::spawn(move || { // Acquire a lock on the mutex. This blocks until the lock is available. // The lock guard ensures exclusive access. 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 function block). thread::sleep(Duration::from_millis(50)); // Simulate some work }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } // Access the final value from the main thread. let final_count = *counter.lock().unwrap(); println!("Final counter value: {}", final_count); // Without Arc and Mutex, directly sharing 'counter' between threads would // result in compile-time errors due to ownership rules and potential data races. }