Sub topic 6
Lock guards and automatic unlocking
This chapter assumes you know ownership, Drop, and how Mutex::new and lock() are called. It explains what lock() returns and when the lock is released.
What lock() returns
Mutex::lock does not return a reference to the data. It returns LockResult<MutexGuard<T>>. After unwrap(), you hold a MutexGuard<T>, which is a value that:
- Dereferences to the protected data, so
*guardand method calls work as with a&mut T. - Owns the lock. While the guard exists, no other thread can lock the mutex.
- Implements
Drop. When the guard is dropped, it unlocks the mutex.
There is no unlock() method. The lock is held for exactly as long as the guard is alive, and Rust's scope rules decide when that ends.
Releasing a guard
A guard is dropped in one of three ways: its scope ends, you call drop(guard), or it was a temporary and its statement ends.
use std::sync::Mutex;
fn main() {
let m = Mutex::new(vec![1]);
{
let mut guard = m.lock().unwrap();
guard.push(2);
} // guard dropped, lock released
let mut guard = m.lock().unwrap();
guard.push(3);
drop(guard); // explicit early release
let len = m.lock().unwrap().len(); // temporary guard, dropped at the semicolon
println!("{len}");
}This prints 3. Use an inner block or drop when work remains in the function after you finish with the data.
Common errors
Locking twice in one thread
A thread that calls lock() while it already holds a guard for the same mutex waits for itself. The standard library says this may deadlock or panic, and you can't rely on either. The usual cause is a forgotten guard that is still in scope.
Temporaries that outlive the loop body
A temporary guard in a while let or match scrutinee lives until the end of the whole construct, not just the line that created it.
use std::sync::Mutex;
fn main() {
let queue = Mutex::new(vec![1, 2, 3]);
// Bad: `while let Some(n) = queue.lock().unwrap().pop() { ... }`
// would keep the lock for the entire loop body.
loop {
let item = queue.lock().unwrap().pop(); // guard dropped at the semicolon
match item {
Some(n) => println!("got {n}"),
None => break,
}
}
}Binding the result with let ends the temporary's life at that statement. The loop body then runs without the lock.
Ignoring that a guard is a value
let _ = m.lock().unwrap(); drops the guard immediately, because _ does not bind. let _guard = ... keeps it alive until the end of the scope. Mixing these up gives you either no protection or a lock held longer than intended.
Related guard behavior
MutexGuardis notSend. The compiler stops you from moving a guard to another thread, because the same thread that locked must unlock.try_lock()returns immediately with an error if the mutex is already locked. It does not wait.Mutex::into_inner()andget_mut()need no guard. They are available when you own the mutex or hold&mutto it, so no other thread can be using it.
Exercise
In the following code, what goes wrong, and how do you fix it without removing either line that uses the data? let m = Mutex::new(0); let mut a = m.lock().unwrap(); a += 1; let b = m.lock().unwrap(); println!("{}", b);
Show answer
The first guard a is still alive when the second lock() runs, so the thread waits for a lock it holds itself. This may deadlock or panic. Fix it by releasing a first, either with drop(a) after *a += 1; or by putting the first two lines in an inner block. Then the second lock() succeeds and prints 1.