Sub topic 3
Mutex Poisoning and Choosing Rust Synchronization Tools
Assume you know Rust ownership, borrowing, lifetimes, move closures, thread::spawn, and basic Result handling. This chapter covers failures and alternatives to the basic Arc<Mutex<T>> pattern.
Mutex poisoning and recovery
A Mutex becomes poisoned when a thread panics while holding its lock. The protected value might be inconsistent, so later calls to lock() return Err(PoisonError).
Recover only when the value remains safe to use:
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let value = Arc::new(Mutex::new(0));
let worker_value = Arc::clone(&value);
let _ = thread::spawn(move || {
let _guard = worker_value.lock().unwrap();
panic!("worker failed");
}).join();
let guard = value
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
println!("recovered: {}", *guard);
}into_inner() deliberately ignores the poison marker. For data that may be partially updated, validate or rebuild it instead.
Deadlock and lock ordering
A deadlock occurs when threads wait forever for locks held by each other. Prevent it by acquiring multiple locks in one global order. For example, always lock account A before account B, using stable IDs rather than the order requested by a caller. Keep lock lifetimes short and avoid calling unknown code while locked.
Alternatives for different workloads
RwLock<T>allows many concurrent readers or one writer. Use it for read-heavy data, but account for writer starvation or implementation-specific fairness.- Atomic types such as
AtomicUsizeprovide lock-free operations for simple counters and flags. They cannot replace a mutex for related fields or complex invariants. thread::scopelets threads borrow local data because all scoped threads finish before the scope returns.
Condvar: waiting for a condition
A Condvar lets a thread sleep until another thread changes shared state. Always check the condition in a loop because wakeups can occur without the condition becoming true.
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use std::time::Duration;
fn main() {
let pair = Arc::new((Mutex::new(false), Condvar::new()));
let worker_pair = Arc::clone(&pair);
thread::spawn(move || {
thread::sleep(Duration::from_millis(10));
let (lock, ready) = &*worker_pair;
*lock.lock().unwrap() = true;
ready.notify_one();
});
let (lock, ready) = &*pair;
let mut done = lock.lock().unwrap();
while !*done {
done = ready.wait(done).unwrap();
}
println!("ready");
}Shared state or message passing?
Use shared state when several threads need coordinated access to the same representation. Use channels when ownership should move between workers and a single receiver can own the resulting state. Channels often reduce lock ordering and poisoning concerns, while a mutex can avoid copying and express shared invariants directly.
Exercise
Which tool fits a shared hit counter, and which fits a producer sending completed jobs to one worker?
Show answer
Use an atomic integer for the counter. Use a channel for completed jobs when ownership can move to the worker.