Use std::sync::atomic types like AtomicU32 with fetch_add and load methods to safely share mutable state between threads.
Use std::sync::atomic types like AtomicU32 to safely share mutable state between threads without locks. These types provide atomic operations that guarantee thread-safe reads and writes.
use std::sync::atomic::{AtomicU32, Ordering};
let counter = AtomicU32::new(0);
// Atomically increment the value
counter.fetch_add(1, Ordering::Relaxed);
// Read the current value
let current = counter.load(Ordering::Relaxed);
Atomic types are special variables that multiple threads can update at the same time without crashing or corrupting data. Think of them like a single, secure turnstile that only lets one person pass at a time, ensuring the count is always accurate. You use them when you need a fast, lock-free way to track numbers or flags across different parts of your program running simultaneously.