Shared State Concurrency
Channels hand data from one thread to another. Sometimes, though, threads genuinely need to share. Rust keeps that safe with Arc (atomic reference counting) and Mutex (mutual exclusion).
Arc<Mutex<T>>: The Shared Mutable State Pattern
use std::sync::{Arc, Mutex};use std::thread;
fn main() { 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());}Piece by piece:
Arc(Atomically Reference Counted) isRc's thread-safe cousin. Atomic ops keep the reference count honest across cores.Mutexprovides mutual exclusion.lock()blocks until the mutex frees up and hands back aMutexGuardthat unlocks automatically on drop.Arc::clonebumps the reference count. Every thread holds its ownArc, all pointing at the sameMutex<i32>.
The type system enforces the rules for you. A spawned thread can't borrow a Mutex<T> from your stack, so sharing one means wrapping it in an Arc (or using scoped threads), and you can't peek inside a Mutex without calling lock(). Sloppy concurrent code dies at compile time.
RwLock: Multiple Readers
When reads vastly outnumber writes, RwLock lets readers run in parallel:
use std::sync::{Arc, RwLock};use std::thread;
fn main() { let data = Arc::new(RwLock::new(vec![1, 2, 3]));
let mut handles = vec![];
// Multiple reader threads for i in 0..5 { let data = Arc::clone(&data); handles.push(thread::spawn(move || { let read = data.read().unwrap(); println!("Reader {}: {:?}", i, *read); })); }
// Single writer thread { let data = Arc::clone(&data); handles.push(thread::spawn(move || { let mut write = data.write().unwrap(); write.push(4); println!("Writer: added 4"); })); }
for h in handles { h.join().unwrap(); }
println!("Final: {:?}", *data.read().unwrap());}RwLock admits any number of readers, or one writer. Never both at once.
Mutex Poisoning
If a thread panics while holding a mutex lock, the mutex becomes poisoned. Subsequent calls to lock() return an Err:
use std::sync::{Arc, Mutex};use std::thread;
fn main() { let data = Arc::new(Mutex::new(0));
// This thread panics while holding the lock let data_clone = Arc::clone(&data); let handle = thread::spawn(move || { let mut guard = data_clone.lock().unwrap(); *guard = 42; panic!("oops!"); });
let _ = handle.join(); // Thread panicked
// Mutex is now poisoned match data.lock() { Ok(guard) => println!("Value: {}", *guard), Err(poisoned) => { // Can still access the data - the value might be inconsistent let guard = poisoned.into_inner(); println!("Poisoned, value: {}", *guard); } }}Poisoning is a safety net. It flags that the data might be half-mutated, because whoever held the lock left in a hurry.
Avoiding Deadlocks
Rust shuts down data races at compile time, but deadlocks remain on you. Lock two mutexes in the wrong order and you'll hang just like in any other language:
// DEADLOCK: Thread 1 locks a then b, Thread 2 locks b then alet a = Arc::new(Mutex::new(1));let b = Arc::new(Mutex::new(2));
// Thread 1let _ga = a.lock().unwrap();let _gb = b.lock().unwrap(); // Deadlock if thread 2 holds b
// Thread 2let _gb = b.lock().unwrap();let _ga = a.lock().unwrap(); // Deadlock if thread 1 holds aStrategies to prevent deadlocks:
- Always lock in the same order (e.g., by address or ID)
- Use try_lock to avoid blocking
- Minimize lock scope - drop guards as soon as possible
- Design to use a single mutex when possible
Interior Mutability Patterns
Sometimes you need to mutate through a shared reference. Rust offers a small toolbox of interior mutability types:
use std::cell::Cell;use std::cell::RefCell;use std::sync::atomic::{AtomicUsize, Ordering};
// Cell<T>: single-threaded; get() needs T: Copy, set/replace/take don'tlet cell = Cell::new(0);cell.set(42);let val = cell.get();
// RefCell<T>: for any type, single-threaded, runtime borrow checkinglet ref_cell = RefCell::new(vec![1, 2, 3]);ref_cell.borrow_mut().push(4);
// Atomic types: for integers, thread-safelet counter = AtomicUsize::new(0);counter.fetch_add(1, Ordering::SeqCst);The Ordering argument says how this atomic operation orders the memory accesses around it, as seen by other threads. SeqCst (sequentially consistent) is the strictest: every thread agrees on one order for all SeqCst operations. For a plain counter that nothing else depends on, Relaxed is enough; Acquire and Release pair up when one thread publishes data and another reads it. When in doubt, start with SeqCst and relax it only with a reason.
| Type | Thread-Safe | Copy Required | Overhead |
|---|---|---|---|
Cell<T> | No | Only for get() | Zero |
RefCell<T> | No | No | Runtime borrow check |
Mutex<T> | Yes | No | OS mutex |
RwLock<T> | Yes | No | OS rwlock |
Atomic* | Yes | N/A (primitives) | Hardware atomic |
Practical Pattern: Thread-Safe Cache
use std::collections::HashMap;use std::sync::{Arc, RwLock};
struct Cache { data: Arc<RwLock<HashMap<String, String>>>,}
impl Cache { fn new() -> Self { Cache { data: Arc::new(RwLock::new(HashMap::new())), } }
fn get(&self, key: &str) -> Option<String> { let read = self.data.read().unwrap(); read.get(key).cloned() }
fn set(&self, key: String, value: String) { let mut write = self.data.write().unwrap(); write.insert(key, value); }
fn get_or_insert(&self, key: &str, compute: impl FnOnce() -> String) -> String { // Try read first if let Some(val) = self.get(key) { return val; }
// Need to write let mut write = self.data.write().unwrap(); // Double-check after acquiring write lock if let Some(val) = write.get(key) { return val.clone(); }
let value = compute(); write.insert(key.to_string(), value.clone()); value }}Double-checked locking — peek under the read lock, then verify again under the write lock — keeps writers rare while still preventing duplicate work.