`Mutex`
Mutex<T> is exclusive locking. lock blocks until it gets a guard, then you may mutate T. Only one guard exists at a time.
Detailed Explanation
A mutex is a lock plus a value. Mutex::new(state) wraps the state. lock() returns LockResult<MutexGuard<T>>. The guard dereferences to T and unlocks when it drops. You do not call unlock. RAII is the API. If you hold the guard across an .await, you have locked an async task-switch — use Tokio's mutex for that, not std::sync::Mutex, unless you are sure you will not yield.
lock can fail with a poison error. Poison means a thread panicked while it held the guard. The data may be half-updated. unwrap on the LockResult panics the new thread too. into_inner on the poison error recovers the data if you have a plan to repair it. Poison is not the default in parking_lot or some other crates; std's mutex has it.
Mutex<T> is the tool for "many threads, one writer at a time, data can be any T". If most access is reads, RwLock allows concurrent readers. If T is a simple integer, an atomic is cheaper. If threads only pass messages, a channel may remove the shared state.
Deadlock is still your problem. Two mutexes locked in opposite order on two threads will hang. Std has no deadlock detector. Keep the lock order consistent, keep the critical section small, and do not call unknown code while you hold the guard.
When you reach for Mutex: shared mutable state across threads. When you reach for RwLock: read-heavy shared state. When you reach for a channel: you can restructure so state is not shared.
Code Examples
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let hits = Arc::new(Mutex::new(0u32));
let mut handles = vec![];
for _ in 0..4 {
let hits = Arc::clone(&hits);
handles.push(thread::spawn(move || {
*hits.lock().unwrap() += 1;
}));
}
for h in handles {
h.join().unwrap();
}
println!("{}", *hits.lock().unwrap()); // prints: 4
}Common Gotchas
A poisoned lock means a panic while holding it
`unwrap` turns that into another panic. Decide whether to recover with `into_inner`.
Lock order is a deadlock
Document a global order, or use one mutex, or use `std::sync::try_lock` only as a last resort.
The guard is the unlock
A guard stored in a struct field stays locked. Scope it tightly.