Arc and Mutex for safe shared mutable state across threads

5175
0

When you need shared mutable state across threads, Arc<Mutex<T>> is the idiomatic pattern. Arc is an atomic reference counter that allows multiple ownership, and Mutex provides interior mutability with runtime locking. You clone the Arc for each thread, giving them all access to the same Mutex. Locking the mutex returns a guard that automatically unlocks on drop, preventing deadlocks from forgotten unlocks. The compiler ensures you can't access the data without locking. This pattern is slower than lock-free alternatives but far safer than raw pointers or C-style mutexes. For read-heavy workloads, I use RwLock instead. The key is that Rust makes shared mutability explicit and safe by default.