In Rust, why does calling `m.lock()` again inside a `match m.lock().unwrap().get(id)` arm hang, and how do you end the `MutexGuard` sooner?
answer
- guard lifetime equals lock lifetime
- scrutinee temporaries outlive the arms
- relocking on one thread never returns
- copy the value out first
- 2024 edition changed if let
basics
~20 sA temporary MutexGuard in a match scrutinee lives until the match ends, so every arm holds the lock and relocking on that thread never returns. Copy the value out in a separate let, or drop a named guard.
solid answer
~40 sThe lock is released when the `MutexGuard` is dropped. In `match m.lock().unwrap().get(id)`, the guard is a temporary of the scrutinee, and Rust keeps scrutinee temporaries alive until the whole `match` ends because the arms may borrow from them; `get` returns a reference into the locked map. std says relocking from the holding thread is unspecified but will not return, so the thread hangs. The fix is to shorten the guard: `let n = m.lock().unwrap().get(id).copied();` drops it at the semicolon, or bind it and call `drop(guard)`, or use an inner block. `let _ = m.lock().unwrap();` does not hold the lock at all and is rejected by the deny-by-default `let_underscore_lock` lint. Since the 2024 edition (Rust 1.85) an `if let` drops its scrutinee temporaries before the `else` block; `match` is unchanged.
code
rust · 30 linesuse std::collections::HashMap;
use std::sync::Mutex;
// try_lock reports the state instead of hanging the way lock() would.
fn held(m: &Mutex<HashMap<String, u32>>) -> bool {
m.try_lock().is_err()
}
fn main() {
let m = Mutex::new(HashMap::from([("client-1".to_string(), 3u32)]));
// The guard is a temporary of the scrutinee: alive in every arm.
match m.lock().unwrap().get("client-1") {
Some(n) if *n >= 3 => println!("in match arm, held = {}", held(&m)),
_ => {}
}
// Copy the value out: the guard dies at the end of the let statement.
let n = m.lock().unwrap().get("client-1").copied();
if let Some(n) = n {
println!("after let ({n}), held = {}", held(&m));
}
// Edition 2024: the scrutinee's guard is dropped before else runs.
if let Some(_) = m.lock().unwrap().get("client-9") {
println!("unknown client limited");
} else {
println!("in else, held = {}", held(&m));
}
}go deeper
Remember that the lock is held exactly as long as the MutexGuard lives, and that a named guard lasts until the end of its block.
Explain temporary lifetime in a match scrutinee, why relocking on the same thread never returns, and the three fixes: copy out in a let, drop the named guard, or an inner block.
Spot the pattern in review, know the 2024 edition shortened only the if let else case, and use try_lock or the significant_drop_in_scrutinee lint to prove or prevent a hang.
Decide which guard-scope rules a team enforces, such as clippy lints and no lock calls in scrutinees, weighing noise against the cost of a hang in production.
## The guard decides when the lock ends A `std::sync::Mutex` is unlocked when its `MutexGuard` is dropped, so "how long is the lock held?" is the same question as "how long does the guard live?". Rust answers that with ordinary scope rules, and two of them matter for locks: - A **named guard** (`let mut map = m.lock().unwrap();`) lives until the end of the enclosing block, unless you `drop(map)` earlier or put it in an inner `{ }` block. - A **temporary guard** — one that is never bound to a name, as in `m.lock().unwrap().get(id)` — lives until the end of the enclosing *statement*, with a few exceptions where the temporary scope is longer. The match scrutinee is the exception that bites. ## Why the match arm hangs In `match m.lock().unwrap().get(id) { .. }`, the guard is a temporary created while evaluating the scrutinee. Rust keeps scrutinee temporaries alive until the **whole `match` ends**, because the patterns may bind references into them — here, `get` returns an `Option<&u32>` that points into the locked map. So every arm runs with the lock held. If an arm then calls `m.lock()` again on the same thread, std documents the result precisely: locking a mutex in the thread that already holds it is *left unspecified*, but `lock` *will not return* — it might panic or deadlock. In practice the request thread hangs and every other thread queues behind it. `try_lock` returns `Err(TryLockError::WouldBlock)` in the same situation, which is how the example on this page shows the state without hanging. ## Ways to end the guard sooner 1. **Copy the value out in its own statement.** `let n = m.lock().unwrap().get(id).copied();` — the temporary guard dies at the semicolon, and the following `match n` runs unlocked. 2. **Name the guard and drop it.** `let map = m.lock().unwrap(); let n = map.get(id).copied(); drop(map);` makes the critical section explicit. 3. **Use an inner block** that ends with the value you need: `let n = { let map = m.lock().unwrap(); map.get(id).copied() };`. 4. **Do all the work under one guard** instead of locking twice: take the guard once, read and update through it, then release it. What *not* to do is write `let _ = m.lock().unwrap();` to "take the lock for the rest of the block": `_` binds nothing, so the guard drops at once. rustc 1.99 rejects that line with the deny-by-default `let_underscore_lock` lint ("non-binding let on a synchronization lock"), and a bare `m.lock().unwrap();` statement warns through `#[must_use]`: "if unused the Mutex will immediately unlock". ## `if let` and the 2024 edition `if let` used to behave like `match`: under the 2021 edition, the scrutinee's temporaries lived until the end of the entire `if let ... else` expression, so the `else` branch also ran with the guard held, and relocking there hung. The **2024 edition** (stable since Rust 1.85) shortened that scope: the temporaries are dropped when the then-block finishes or *before control enters the `else` block*. | Construct | Guard from the scrutinee lives until | |---|---| | `match m.lock().unwrap().get(id) { .. }` | end of the whole `match`, every edition | | `if let .. = m.lock().unwrap().get(id) { .. }` (then-block) | at least through the then-block, every edition | | `.. else { .. }` under edition 2021 | end of the whole expression — `else` still locked | | `.. else { .. }` under edition 2024 | dropped before `else` starts | | `let n = m.lock().unwrap().get(id).copied();` | end of that statement | Two points still hold under 2024: the then-block of `if let` and the body of `while let` run with the guard alive, and `match` did not change at all. The edition change in full is covered in the material on the 2024 edition. ## Habits that catch it - Keep a lock call out of a `match` scrutinee unless the arms genuinely need the guard. - Treat any second `lock()` on the same mutex inside one function as a review flag. - Clippy's allow-by-default `significant_drop_in_scrutinee` lint flags exactly this pattern; some teams enable it. - Two different mutexes locked in opposite orders by two threads is the other classic hang; keeping each guard's scope short is what makes such a cycle visible in review.
- What exactly does std promise when a thread calls `lock()` on a `std::sync::Mutex` it already holds?Only that `lock` will not return. The docs leave the exact behaviour unspecified — it might deadlock or it might panic — and its Panics section says it might panic in that case. Code must never rely on either outcome; std's `Mutex` is not reentrant, so the fix is to restructure so one guard covers the work.
- Does the 2024 edition change make `if let Some(n) = m.lock().unwrap().get(id) { m.lock(); }` safe?No. Under the 2024 edition the scrutinee's temporaries are dropped before the `else` block, but the then-block still runs with the guard alive, because `n` borrows from the locked map. Relocking inside the then-block hangs exactly as it does in a `match` arm.
- Why does rustc reject `let _ = m.lock().unwrap();` instead of just warning?The pattern `_` binds nothing, so the guard is dropped at the end of the statement and the mutex is unlocked immediately; the line looks like it takes the lock for the block but protects nothing. The `let_underscore_lock` lint is deny-by-default in rustc 1.99 for that reason. Bind a real name such as `_guard` if you mean to hold it.
- A temporary guard in a match scrutinee is dropped as soon as get returns
- Locking a std Mutex twice on the same thread just succeeds because it is the owner
- let _ = m.lock().unwrap() holds the lock until the end of the block
- The 2024 edition also shortened guard lifetimes in match scrutinees
- Calling .copied() at the end of the chain still keeps the guard alive until the block ends
Assumes Rust 1.99 on the 2024 edition (stable since 1.85), which drops if let scrutinee temporaries before the else block; match scrutinee scope is the same in every edition.