Sub topic 2
Lock Guards and Automatic Unlocking
Assume Rust ownership, borrowing, lifetimes, closures, move, and basic thread spawning. This chapter focuses on how a mutex guard controls access to shared data.
Lock guards release locks automatically
A Mutex<T> protects a value of type T. Calling lock waits until the mutex is available and returns a MutexGuard<T>. The guard lets you access the protected value through dereferencing.
The guard also owns the lock. When the guard leaves its scope, Rust runs its Drop implementation and unlocks the mutex. This prevents a thread from forgetting to release the lock.
use std::sync::Mutex;
fn main() {
let value = Mutex::new(0);
{
let mut guard = value.lock().unwrap();
*guard += 1;
} // guard is dropped; the mutex is unlocked
println!("{}", *value.lock().unwrap());
}lock returns a Result because another thread may have panicked while holding the mutex. Calling unwrap is suitable when that failure should stop the program. Recovery is discussed separately when the data may still be usable.
Putting it together: `Arc<Mutex<T>>`
Arc<T> provides shared ownership between threads. Mutex<T> provides exclusive access to the shared value. Together, Arc<Mutex<T>> is the standard pattern for shared mutable state.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = Vec::new();
for _ in 0..4 {
let counter = Arc::clone(&counter);
handles.push(thread::spawn(move || {
let mut guard = counter.lock().unwrap();
*guard += 1;
}));
}
for handle in handles {
handle.join().unwrap();
}
println!("{}", *counter.lock().unwrap());
}Each thread owns an Arc clone. The mutex ensures that only one thread changes the counter at a time.
Keep critical sections short
A critical section is code executed while a lock is held. Do slow work before locking, and copy or remove the needed data inside the lock. Use an inner block when you want to release the guard before the surrounding scope ends.
Holding a lock during file access, network calls, or long calculations makes other threads wait and can increase deadlock risk.
Exercise
What releases a Rust mutex after lock() succeeds?
Show answer
The MutexGuard releases it when the guard is dropped, usually when it leaves its scope.