Locking provides mutual exclusion: at most one thread can access a protected resource at a time. In Rust, std::sync::Mutex provides this protection while still allowing a value to change through an otherwise immutable binding. section 10.3.3 section 10.3
use std::sync::Mutex;
fn main() {
let my_mutex = Mutex::new(5); #1
let mut mutex_changer = my_mutex.lock().unwrap(); #2
println!("{my_mutex:?}"); #3
println!("{mutex_changer:?}"); #4
*mutex_changer = 6;
#5
println!("{mutex_changer:?}"); #6
}
Calling .lock().unwrap() returns a MutexGuard. Treat the guard like a locked door: while it exists, change the protected value through it. section 10.3.3
A simple locking workflow is:
- Create a Mutex with the value it should protect. section 10.3.3
- Call .lock() to obtain a MutexGuard, then change the value through the guard. section 10.3.3
- Release the lock by letting the guard leave its scope or by passing it to drop(). section 10.3.3
- Use .try_lock() when waiting indefinitely would be unsafe; it reports failure instead of blocking forever. section 10.3.3 section 10.4
Incrementing a protected value
A compact update is *my_mutex.lock().unwrap() += 1;. Repeating this in a loop locks the value for each update and releases the guard at the end of the statement. Holding a second lock on the same Mutex with .lock() can wait forever, causing a deadlock. section 10.3.3

















