Drop The Mutex Guard To Shrink Critical Sections
MutexGuard owns the lock for its lifetime: probe with try_lock, call drop to end the critical section early, or bound the guard with a plain block scope.
Code
use std::sync::Mutex;
fn main() {
let stats = Mutex::new(vec![3, 1, 2]);
// MutexGuard 拥有锁直到被丢弃:guard 活着,其余加锁请求都被挡住
let guard = stats.lock().unwrap();
let total: i32 = guard.iter().sum();
// try_lock 是探测:临界区未结束,二次加锁必然失败
assert!(stats.try_lock().is_err());
// drop 显式提前归还锁:慢速工作不再占用临界区
drop(guard);
assert!(stats.try_lock().is_ok());
// 块作用域约束 guard 生命周期:离开块自动解锁,忘写 drop 也安全
{
let mut guard = stats.lock().unwrap();
guard.push(total);
}
assert!(stats.try_lock().is_ok());
let done = stats.lock().unwrap();
println!("stats: {:?}, total: {}", *done, total);
}What the code does
Count the function main as the entire surface area of Drop The Mutex Guard To Shrink Critical Sections.
Applying it
The demo output is labeled (stats:), so every printed line maps back to its originating operation.
Statements that matter
let total: i32 = guard.iter().sum();
let mut guard = stats.lock().unwrap();
let guard = stats.lock().unwrap();
Interactive Tools for This Topic
FAQ
- What does Drop The Mutex Guard To Shrink Critical Sections print when run?
- Invoke the file as-is — the `stats:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.