Atomicity means an operation is indivisible: other threads cannot observe it halfway through. They see it either fully completed or not performed. section 12.3
This matters when threads update shared data. Without atomic protection, two threads can read the same value, both add one, and accidentally lose an update. section 12.3
Counting safely across threads
Arc shares ownership between threads, while Mutex protects access to the value. In the example, two threads each increment a shared number ten times, producing 20 instead of a smaller, unpredictable result. section 12.3
use std::sync::{Arc, Mutex};
fn main() {
let my_number = Arc::new(Mutex::new(0));
let cloned_1 = Arc::clone(&my_number);
let cloned_2 = Arc::clone(&my_number);
let thread1 = std::thread::spawn(move || { #1
for _ in 0..10 {
*cloned_1.lock().unwrap() += 1; #2
}
});
let thread2 = std::thread::spawn(move || { #3
for _ in 0..10 {
*cloned_2.lock().unwrap() += 1;
}
});
thread1.join().unwrap();
thread2.join().unwrap();
println!("Value is: {my_number:?}");
println!("Exiting the program");
}
Shows Arc cloning, thread creation, locking, and atomic updates to shared state. section 12.3












