Sub topic 6
Lock guards and automatic unlocking
This chapter assumes you know Rust ownership and borrowing, the Drop trait at a basic level, and how Arc<T> and Mutex<T> are introduced. It focuses on the value that Mutex::lock returns, which is how a lock gets released.
What lock() returns
Mutex has no unlock method. Calling lock() returns LockResult<MutexGuard<'_, T>>. After you unwrap it, you hold a MutexGuard, a small value that represents your ownership of the lock.
The guard does three jobs:
- Access. It implements
DerefandDerefMut, so*guardreads and writes the protected data. Method calls such asguard.push(1)work through auto-deref. - Borrowing. It carries a lifetime tied to the
Mutex. The guard cannot outlive the mutex it came from. - Release. Its
Dropimplementation unlocks the mutex. The lock is held exactly as long as the guard exists.
This is the RAII pattern (resource acquisition is initialization). Because the data is reachable only through the guard, you cannot touch it without holding the lock, and you cannot forget to release it.
use std::sync::Mutex;
fn main() {
let m = Mutex::new(5);
{
let mut guard = m.lock().unwrap();
*guard += 1;
println!("inside: {}", *guard);
// try_lock does not block. It fails while another guard exists.
assert!(m.try_lock().is_err());
} // guard dropped here, lock released
assert!(m.try_lock().is_ok());
println!("after: {}", *m.lock().unwrap());
}This prints inside: 6 and then after: 6. try_lock is a useful probe when you learn guards. It returns an error immediately if the lock is taken, where lock would wait.
The lock's lifetime follows the guard
Each guard is a ticket. Only one ticket exists at a time, and returning it is the only way another thread gets one.
When exactly does the guard drop?
A named guard drops at the end of its enclosing block, in reverse order of declaration, like any local. Most surprises come from unnamed guards, which are temporaries. A temporary guard drops at the end of the full statement that created it.
| Code | Guard dropped |
|---|---|
| `let mut g = m.lock().unwrap();` | End of the enclosing block, or at `drop(g)` |
| `let n = m.lock().unwrap().len();` | End of that statement |
| `*m.lock().unwrap() += 1;` | End of that statement |
| `match *m.lock().unwrap() { ... }` | End of the whole `match` |
| `let _ = m.lock().unwrap();` | Immediately, at the end of that statement |
| `let _g = m.lock().unwrap();` | End of the enclosing block |
The following program shows the temporary cases working in your favor:
use std::sync::Mutex;
fn main() {
let m = Mutex::new(vec![1, 2, 3]);
let len = m.lock().unwrap().len(); // lock released at the semicolon
m.lock().unwrap().push(len as i32 + 1); // locked again, then released
println!("{:?}", m.lock().unwrap());
}It prints [1, 2, 3, 4]. Every lock() here succeeds because no guard survives past its statement. Using the guard and discarding it in one expression is the safest way to keep a critical section short.
Guards held by a match
The match row in the table is the common trap. The scrutinee (the expression after match) is evaluated once, and temporaries created in it live until the whole match ends. The lock stays held through every arm.
use std::sync::Mutex;
fn main() {
let m = Mutex::new(Some(3));
match *m.lock().unwrap() {
Some(n) => {
// The temporary guard is still alive in this arm.
println!("got {n}, lock still held: {}", m.try_lock().is_err());
}
None => {}
}
println!("after match, lock free: {}", m.try_lock().is_ok());
}The output is got 3, lock still held: true and then after match, lock free: true. If an arm called m.lock() instead of try_lock(), the thread would try to lock a mutex it already holds. The standard library documents this as unspecified: it may deadlock or panic.
The fix is to copy the value out in its own statement so the guard drops first:
use std::sync::Mutex;
fn main() {
let m = Mutex::new(Some(3));
let current = *m.lock().unwrap(); // guard gone after this line
match current {
Some(n) => {
*m.lock().unwrap() = Some(n + 1); // safe: nothing holds the lock
}
None => {}
}
println!("{:?}", *m.lock().unwrap());
}This prints Some(4). It works because Option<i32> is Copy. For non-Copy data, use .clone() or pull out just the field you need.
The rules for if let scrutinee temporaries changed in the 2024 edition. They now drop before the else block. Do not rely on that difference. Copying the value out first behaves the same in every edition.
Releasing early with drop
Sometimes you want the lock released before the end of the block, and a nested { ... } block would be awkward. Move the guard into drop:
use std::sync::Mutex;
fn main() {
let m = Mutex::new(0);
let _ = m.lock().unwrap(); // `_` does not bind, so the guard drops at once
assert!(m.try_lock().is_ok());
let mut guard = m.lock().unwrap();
*guard += 10;
assert!(m.try_lock().is_err());
drop(guard); // explicit early release; `guard` is moved and unusable now
assert!(m.try_lock().is_ok());
println!("done: {}", *m.lock().unwrap());
}It prints done: 10. The line let _ = m.lock().unwrap(); is a classic bug. It looks like it takes the lock for the rest of the scope, but the pattern _ binds nothing, so the guard is dropped immediately. Write let _guard = ... when you want the lock held only for its side effect, such as serializing access to something outside the mutex.
Because drop(guard) moves the guard, the borrow checker blocks any later use of guard. You cannot read the data after releasing the lock by mistake.
Returning values from guarded code
A function can lock, work, and return plain data. Since the guard is a local, it drops when the function returns:
use std::sync::{Arc, Mutex};
use std::thread;
fn bump(counter: &Mutex<u32>) -> u32 {
let mut guard = counter.lock().unwrap();
*guard += 1;
*guard // copied out; the guard drops as the function returns
}
fn main() {
let counter = Arc::new(Mutex::new(0));
let handles: Vec<_> = (0..4)
.map(|_| {
let counter = Arc::clone(&counter);
thread::spawn(move || {
for _ in 0..3 {
bump(&counter);
}
})
})
.collect();
for handle in handles {
handle.join().unwrap();
}
println!("{}", *counter.lock().unwrap());
}The program prints 12. Passing &Mutex<u32> instead of &Arc<Mutex<u32>> keeps bump independent of how the mutex is shared. &Arc<Mutex<u32>> coerces to &Mutex<u32> at the call site.
You cannot return a reference into the protected data. A function like fn first(m: &Mutex<Vec<i32>>) -> &i32 { &m.lock().unwrap()[0] } fails to compile, because the reference would point through a guard that is dropped when the function ends. The compiler rejects it with a "temporary value dropped while borrowed" error. Return a copy or clone, or return the guard itself, which keeps the lock held by the caller.
Guards cannot cross threads
MutexGuard does not implement Send. A guard must be dropped on the thread that locked it, because some operating system mutexes require that the unlocking thread be the locking thread. The compiler enforces this. You cannot move a guard into thread::spawn, and a guard cannot be held across an .await in a task that may move between threads. Pass the Arc to the other thread and lock there.
Summary of the model
lock()returns a guard, and the guard is the lock.- Dropping the guard is the only way to unlock, whether by scope end,
drop, or statement end for temporaries. - Temporaries in a
matchscrutinee live for the wholematch. let _ = ...releases at once, andlet _name = ...holds.- The guard borrows the mutex and is not
Send, so the compiler stops you from leaking access.
Exercise
In the code below, will second succeed, block forever, or panic? Say which line is responsible and how you would restructure the code so the second lock is safe.
use std::sync::Mutex;
fn main() {
let m = Mutex::new(vec![1, 2, 3]);
match m.lock().unwrap().first() {
Some(&n) => {
let second = m.lock().unwrap();
println!("{n} {}", second.len());
}
None => {}
}
}
Show answer
It does not succeed. The guard from m.lock().unwrap() in the match scrutinee is a temporary that lives until the whole match ends, and the Some(&n) pattern borrows from it. The inner m.lock() on the same thread then tries to lock a mutex that is already held. The standard library says this may deadlock or panic, and on most platforms it blocks forever. Fix it by copying the value out in its own statement, let first = m.lock().unwrap().first().copied();, so the guard drops at the semicolon. Then match first { Some(n) => { let second = m.lock().unwrap(); ... } ... } locks only once at a time.