Sub topic 5
Mutex: one thread at a time
This chapter assumes you know Rust ownership and borrowing, closures with move, and thread::spawn with JoinHandle. You should also be comfortable with Result and unwrap. Here we look at Mutex<T> on its own. Sharing it across threads with Arc comes in the next chapters.
What a Mutex does
A Mutex<T> (mutual exclusion lock) wraps a value and allows only one thread at a time to reach it. A thread that wants the data must first call lock(). If another thread holds the lock, the caller blocks until it is released.
Two design choices set Rust's Mutex apart from locks in many other languages:
- The mutex owns the data. The value of type
Tlives inside the mutex, so there is no way to touch it without locking. - The lock is tied to a value, not to a convention. You cannot forget to lock, because the only path to the data goes through
lock().
Using a Mutex on one thread
The API is easiest to see without threads.
use std::sync::Mutex;
fn main() {
let m = Mutex::new(5);
{
let mut num = m.lock().unwrap();
*num += 1;
} // lock released here
println!("{:?}", m);
}Mutex::new(5) creates the mutex. lock() returns LockResult<MutexGuard<i32>>. The unwrap() takes the guard out of the Ok case. Dereferencing the guard with *num gives access to the inner i32. The inner block ends the guard's life, which releases the lock. The next chapter covers guards in detail.
Note that m is not declared mut. Locking needs only a shared reference (&self). This is called interior mutability: the mutex lets you mutate through a shared reference, and it enforces the exclusivity rules at runtime instead of compile time.
Why lock() returns a Result
lock() fails only if another thread panicked while holding the lock. This state is called poisoning, and a later chapter covers it. For now, unwrap() is the usual choice: if a thread died halfway through updating the data, panicking here is often the right response.
Related methods
| Method | Behavior |
|---|---|
| `lock()` | Blocks until the lock is free, then returns a guard. |
| `try_lock()` | Returns immediately. It gives an error if the lock is held or poisoned. |
| `into_inner()` | Consumes the mutex and returns the value. No locking is needed because you own it. |
| `get_mut()` | Gives `&mut T` when you have `&mut Mutex<T>`. Again, no locking is needed. |
Here is try_lock in action:
use std::sync::Mutex;
fn main() {
let m = Mutex::new(1);
let first = m.lock().unwrap();
// The lock is held, so a second attempt fails instead of blocking.
assert!(m.try_lock().is_err());
drop(first);
assert!(m.try_lock().is_ok());
println!("lock is free again");
}Common errors
- Locking twice on the same thread. If you call
lock()while your own thread still holds a guard, the behavior is unspecified. It may deadlock or panic. Drop the first guard before locking again. - Moving a plain
Mutexinto several threads. Amoveclosure takes ownership, so only the first thread gets the mutex. The compiler reports "use of moved value". The fix is shared ownership, which is the job ofArcin the next chapters. (Scoped threads are another way, covered later.) - Using
try_lockas a casual shortcut. It is for cases where doing other work is better than waiting. A failedtry_lockis not a sign that something is broken.
How the pieces connect
Exercise
A Mutex<i32> is declared with let m = Mutex::new(0);, without mut. Why can *m.lock().unwrap() += 1; still compile?
Show answer
lock() takes &self, so a shared reference is enough. The mutex provides interior mutability: it hands out exclusive access to the inner value through the guard and enforces exclusivity at runtime by blocking other threads.