Learning question: How does Rust make sure a lock is released on every path out of a function, including the ones you did not write?
Acquiring a resource is one line. Releasing it has to happen on the normal path, on every early return, and when something panics. This article reads std::sync::MutexGuard, the value lock() returns, to find where the release is written.
Scope. We read library/std/src/sync/poison/mutex.rs and library/std/src/thread/join_handle.rs at Rust 1.100.0 [S3]. We do not cover Arc, deadlocks, or async mutexes. You need scopes and the idea of a value being moved. RAII, resource acquisition is initialization, is the C++ name for tying a resource's lifetime to an object's; the Rust patterns book credits it to Stroustrup's work in the 1980s and describes Rust's version as Drop plus ownership [S2, ch. 12, "RAII patterns in Rust"].
A guard that was let go and then asked to work
Example 1 locks a ledger, releases the lock by hand, and then writes to the ledger.
Example 1. Does not compile (compile-fail/cf12_raii.rs, lines 4 to 7)
let ledger = Mutex::new(vec![1, 2, 3]);
let mut guard = ledger.lock().unwrap();
drop(guard);
guard.push(4);
The guard was acquired on line 5 and dismissed on line 6. On line 7 it was asked to push a number, as if a night watchman who had handed in his keys could still be sent round to check the doors. The line took the guard's name to be enough. The compiler reported that the name no longer had a value.
error[E0382]: borrow of moved value: `guard`
--> cf12_raii.rs:7:5
|
5 | let mut guard = ledger.lock().unwrap();
| --------- move occurs because `guard` has type `std::sync::MutexGuard<'_, Vec<i32>>`, which does not implement the `Copy` trait
6 | drop(guard);
| ----- value moved here
7 | guard.push(4);
| ^^^^^ value borrowed here after moveWithout this rule, line 7 would be a write to shared data with the lock already released, which is the data race the mutex exists to prevent.
Predict
Mutex has no unlock method you can call. Before reading on: in a version of Example 1 with no drop(guard) line at all, at which character of the source does the mutex become unlocked?
Name the parts
| Part | In std | Where [S3] |
|---|---|---|
| The resource | the lock inside Mutex<T> |
mutex.rs |
| Acquisition | Mutex::lock(&self) |
line 490 |
| The guard | MutexGuard<'a, T> |
line 277 |
| Release | impl Drop for MutexGuard |
lines 741 to 748 |
Where is the unlock?
Pairing every lock with an unlock by hand means every return and every ? between them is a place to forget. Thankfully, the release can belong to a value. Take a look at Example 2.
Example 2. Acquire, hold, release (library/std/src/sync/poison/mutex.rs, lines 490 to 495, 277 to 280 and 741 to 748, attributes removed [S3])
pub fn lock(&self) -> LockResult<MutexGuard<'_, T>> {
unsafe {
self.inner.lock();
MutexGuard::new(self)
}
}
pub struct MutexGuard<'a, T: ?Sized + 'a> {
lock: &'a Mutex<T>,
poison: poison::Guard,
}
impl<T: ?Sized> Drop for MutexGuard<'_, T> {
fn drop(&mut self) {
unsafe {
self.lock.poison.done(&self.poison);
self.lock.inner.unlock();
}
}
}
There are three pieces. lock takes the lock and returns a MutexGuard. The guard holds lock: &'a Mutex<T>, a borrow of the mutex, so the mutex cannot be destroyed while a guard exists: rustc 1.100.0 rejects a guard that outlives its mutex with E0597 (evidence/ev12_mutex_outlived_by_guard.rs and .stderr, beside this article).¹ And Drop is the trait whose drop method runs when a value's owner goes away [S4]. Its body here is the unlock. The answer to the prediction: the closing brace of the scope that owns the guard.
The first line of that
drop body is the other half of the story. poison.done records whether the thread is panicking (library/std/src/sync/poison.rs lines 125 to 129), so that a mutex released by a panic is marked, and the next lock() returns an Err, with the guard inside it, as a warning that the data may be half-updated [S3, mutex.rs lines 24 to 29 and 465 to 467].
What transfers, and what does not
try { ... } finally { $lock->release(); } is how you would write this in PHP, and __destruct exists [S5]. The goal transfers. What does not is where the timing comes from. The PHP manual says a destructor is called as soon as there are no other references to the object, or in any order during the shutdown sequence [S5], so the moment depends on what else holds a reference while the program runs. drop runs at a point you can find by reading the source: the end of the owning scope, or the line where the value is moved into something that ends. And the type's author writes the release once, where a finally is written by every caller.
What does not get cleaned up?
So the lock is released on every path that leaves the scope: the Rust Reference says that when control flow leaves a drop scope its variables are dropped, and that returning from a function leaves several scopes at once [S4]. The exceptions it lists end the process without unwinding, std::process::exit and a panic handler set to abort among them. Drop is the right tool when the cleanup is local, cannot fail, and has nothing to report, and it is the wrong tool for the rest: std's own JoinHandle shows where the line is, because dropping one does not wait for its thread and does not stop it, and the documentation says the thread is detached, with no handle left and no way to join it [S3, join_handle.rs lines 9 to 11], so work that must finish before the program exits needs a call you make and a result you look at. Of the things your program must do on the way out, which can be done in a destructor that returns nothing?
Practice tier: compiler, for the release itself. Lint tier for one trap: let _ = ledger.lock(); would drop the guard at once, and rustc 1.100.0 refuses to compile it: the lint let_underscore_lock, deny by default, reports "this lock is not assigned to a binding and is immediately dropped" (evidence/ev12_let_underscore.stderr, beside this article). The attribute on MutexGuard says the same in its own words: #[must_use = "if unused the Mutex will immediately unlock"] (line 270).
Testing
The claim is that the lock is held exactly as long as the guard lives. Example 3 would fail if the guard released early or late.
Example 3. Locked inside the scope, unlocked after it (tests/p12_raii_mutex_guard.rs, first test)
let ledger = Mutex::new(vec![1, 2, 3]);
{
let mut guard = ledger.lock().unwrap();
guard.push(4);
assert!(matches!(ledger.try_lock(), Err(TryLockError::WouldBlock)));
} // guard dropped here
assert_eq!(ledger.try_lock().unwrap().len(), 4);
It passed on rustc 1.100.0. A second test panics in a thread while holding the guard and asserts that afterwards ledger.is_poisoned() is true and try_lock returns TryLockError::Poisoned: the lock was released, and marked. Early return is not in the test file. It was run separately on rustc 1.100.0 (evidence/ev12_early_return.rs), and the Reference states the rule [S4].
Retrieve
- Which trait's method contains the call to
unlock? - What happens to a thread when its
JoinHandleis dropped?
This closes a loop from the Builders article: spawn returned a JoinHandle, and now you know what ignoring it means.
TL;DR
Mutex::lock returns a MutexGuard, and the mutex is unlocked by the guard's Drop implementation, which runs when the guard's owner goes out of scope, on normal exit, early return and an unwinding panic alike. Using the guard after dropping it is a compile error. Drop suits local cleanup that cannot fail; a JoinHandle is not joined by being dropped.
¹ The 'a is a lifetime: the compiler's name for "how long this borrow lasts". You do not have to write it when you call lock().