use std::sync::{Arc, Mutex}; use std::thread; fn main() { // Arc (Atomic Reference Count) allows shared ownership across multiple threads. // Mutex provides mutual exclusion, ensuring only one thread can access the // inner data at a time, preventing data races. let counter = Arc::new(Mutex::new(0)); let mut handles = vec![]; for i in 0..10 { // Clone the Arc to create a new ownership for each thread. // This increments the reference count. let counter_clone = Arc::clone(&counter); let handle = thread::spawn(move || { // Lock the mutex to get a mutable reference to the inner data. // This blocks until the lock is acquired. let mut num = counter_clone.lock().unwrap(); // panics on poisoning *num += 1; println!("Thread {} increased counter to {}", i, *num); // The lock is automatically released when `num` goes out of scope // at the end of the closure. }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } println!("Final counter value: {}", *counter.lock().unwrap()); assert_eq!(*counter.lock().unwrap(), 10); }