Sub topic 5
Mutex: one thread at a time
This chapter assumes you know Rust ownership and borrowing, closures and move, thread::spawn with JoinHandle, and Result with unwrap. You don't need Arc yet. The next chapters combine it with Mutex. Here we study Mutex<T> by itself.
What a mutex is
A mutex (short for mutual exclusion) is a lock that lets only one thread use a piece of data at a time. A thread that wants the data asks for the lock. If nobody holds it, the thread gets it. If another thread holds it, the asking thread sleeps until the lock is free.
The previous chapters showed why unsynchronized mutation across threads is a problem. A Mutex fixes it by turning "many threads may touch this" into "one thread at a time may touch this".
The data lives inside the mutex
In C or Java, a mutex is usually a separate object that you must remember to lock before touching some other variable. Nothing stops you from forgetting.
Rust's std::sync::Mutex<T> owns the data it protects. You cannot reach the T without going through the lock.
use std::sync::Mutex;
fn main() {
let m = Mutex::new(5);
{
let mut num = m.lock().unwrap();
*num += 1;
}
println!("{:?}", m);
}This prints Mutex { data: 6, poisoned: false, .. }.
Four things happen here:
Mutex::new(5)moves the value5into the mutex. The variablemhas typeMutex<i32>, noti32.m.lock()blocks until the lock is available, then returns aResult.unwrap()extracts aMutexGuard<i32>. The guard behaves like a mutable reference:*num += 1changes the data.- At the closing brace,
numgoes out of scope and the lock is released.
Notice that m is not declared mut, yet we changed the value. lock takes &self, so a shared reference is enough. This is called interior mutability: the mutex checks the exclusivity rule at run time instead of the compiler checking it at compile time. The next chapter covers the guard and its automatic unlocking in detail.
What happens when two threads compete
When a second thread calls lock while the first holds it, the second thread blocks. The operating system puts it to sleep, so it uses no CPU while it waits.
Here is a runnable program with real threads. A static mutex is shared by every thread without an Arc, because a static lives for the whole program. Mutex::new is a const fn since Rust 1.63, so it can initialize a static.
use std::sync::Mutex;
use std::thread;
static COUNTER: Mutex<u32> = Mutex::new(0);
fn main() {
let handles: Vec<_> = (0..4)
.map(|_| {
thread::spawn(|| {
for _ in 0..1000 {
*COUNTER.lock().unwrap() += 1;
}
})
})
.collect();
for handle in handles {
handle.join().unwrap();
}
println!("{}", *COUNTER.lock().unwrap());
}The output is always 4000. Each increment happens entirely inside one lock, so no update is lost. The guard returned by lock() is a temporary here, so it is dropped at the end of the statement.
The ordering of threads is not defined. A mutex gives you exclusion, not fairness. The standard library does not promise that waiting threads get the lock in the order they asked.
The methods you will use
| Method | Blocks? | Returns | Use it when |
|---|---|---|---|
| `lock()` | Yes | `LockResult<MutexGuard<T>>` | You need the data and can wait. |
| `try_lock()` | No | `TryLockResult<MutexGuard<T>>` | You would rather do something else than wait. |
| `get_mut()` | No | `LockResult<&mut T>` | You have `&mut Mutex<T>`, so no other thread can hold it. |
| `into_inner()` | No | `LockResult<T>` | You own the mutex and want the data back. |
| `is_poisoned()` | No | `bool` | You want to inspect the poison flag without locking. |
Why lock returns a Result
lock returns a Result because a mutex can be poisoned. If a thread panics while holding the guard, the data may be half-updated. The mutex remembers this, and every later lock returns Err. Most code calls unwrap(), which turns one thread's panic into a panic in the next thread that locks. Poisoning has its own chapter. For now, read lock().unwrap() as "get the lock, and crash if a previous holder crashed".
Trying without waiting
try_lock returns immediately. If the lock is taken, you get Err(TryLockError::WouldBlock).
use std::sync::{Mutex, TryLockError};
fn main() {
let m = Mutex::new(String::from("hello"));
let first = m.lock().unwrap();
match m.try_lock() {
Ok(_) => println!("got it"),
Err(TryLockError::WouldBlock) => println!("busy"),
Err(TryLockError::Poisoned(_)) => println!("poisoned"),
}
println!("{}", first);
}This prints busy, then hello. The first guard is still alive when try_lock runs, so the second attempt fails. This is useful for opportunistic work, such as a background task that skips a refresh if someone else is already using the data.
Getting the data out
If you own the mutex, you don't need to lock it. Locking is only needed to coordinate with other threads, and ownership proves there are none.
use std::sync::Mutex;
fn main() {
let mut m = Mutex::new(vec![1, 2]);
m.get_mut().unwrap().push(3);
let v = m.into_inner().unwrap();
println!("{:?}", v);
}This prints [1, 2, 3]. get_mut needs &mut Mutex<T>, so the borrow checker guarantees exclusivity and no run-time locking happens. into_inner consumes the mutex. Both still return a Result for the poisoning case.
What a mutex does not protect you from
A mutex prevents data races, which are unsynchronized simultaneous accesses where at least one is a write. It does not prevent logic races, where your program's steps are individually safe but together wrong.
Here is a classic example:
use std::sync::Mutex;
fn main() {
let balance = Mutex::new(100);
// Wrong: check and update use two separate locks.
let enough = *balance.lock().unwrap() >= 80;
if enough {
// Another thread could withdraw between these two lines.
*balance.lock().unwrap() -= 80;
}
// Right: one lock covers both the check and the update.
let mut guard = balance.lock().unwrap();
if *guard >= 80 {
*guard -= 80;
}
println!("{}", *guard);
}In this single-threaded demo both versions run safely, so the first block is only a pattern to avoid. With several threads, the first version can let two withdrawals both pass the check. The second version holds one guard across the check and the update, so the pair acts as a single step. The rule is that a lock must cover the whole invariant, meaning everything that must stay consistent. How long to hold it is the subject of the chapter on critical sections.
Common errors
- Locking twice on one thread. Calling
lock()while the same thread already holds the guard may deadlock or panic. The standard library does not define which. Mutexes in Rust are not reentrant. - Forgetting the data is wrapped.
Mutex<i32>is not ani32. You must lock, then dereference with*. - Expecting a copy.
lock()gives access to the single shared value. Cloning the guard's contents gives you a snapshot, not a link to the original. - Using a
Mutexacross threads without shared ownership. Moving aMutexinto one thread's closure takes it away from all the others. Sharing the same mutex needs astatic, scoped threads, orArc.
Summary
Mutex<T>owns its data and grants access to one thread at a time.lock()blocks and returns a guard.try_lock()returns immediately.get_mut()andinto_inner()skip locking when you have exclusive access.- The mutex stops data races but not logic races. One guard should cover the whole check-and-update sequence.
- A single
Mutexcan only be shared directly through astatic, scoped threads, orArc.
Exercise
A worker thread calls let a = counter.lock().unwrap(); and, a few lines later in the same scope while a is still alive, calls counter.lock().unwrap() again. Why is this a bug, and how would try_lock behave in the same situation?
Show answer
Rust's Mutex is not reentrant. The second lock() waits for a lock that the same thread already holds, so it can never succeed. It may deadlock or panic, and the standard library does not say which. try_lock() would not hang. It would return Err(TryLockError::WouldBlock) because the lock is taken. The fix is to reuse the existing guard a or drop it before locking again.
Exercise
You own a Mutex<Vec<u32>> named m and no other thread can reach it. Which two methods let you work with the vector without locking, and what does each require?
Show answer
get_mut() requires &mut m, and gives &mut Vec<u32> (inside a LockResult). into_inner() requires ownership of m, consumes it, and returns the Vec<u32> (also inside a LockResult). Neither locks, because exclusive access or ownership already proves no other thread holds the mutex.