use std::sync::{Arc, Mutex}; // Rc is not thread safe, but Arc is. (Atomic Reference Count) use std::thread; fn single_thread_example() { let m = Mutex::new(5); { let mut num = m.lock().unwrap(); *num = 6; } // Reference to mutex value goes out of scope, lock is released println!("m = {:?}", m); } fn multi_thread_example() { let counter = Arc::new(Mutex::new(0)); let mut handles = vec![]; for _ in 0..10 { let counter = Arc::clone(&counter); let handle = thread::spawn(move || { let mut num = counter.lock().unwrap(); *num += 1; }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } println!("Result: {}", *counter.lock().unwrap()); } fn main() { single_thread_example(); multi_thread_example(); }