Manage shared state with `std::sync::Mutex`
A Mutex (Mutual Exclusion) ensures that only one thread can access data at a time.
lock(): Blocks the current thread until the lock is acquired. Returns aMutexGuard(a smart pointer) that provides mutable access to the inner data viaDerefandDrop.- The lock is automatically released when the
MutexGuardgoes out of scope. - To share a
Mutexacross multiple threads, it must be wrapped in an atomically reference-counted pointer (Arc), asRcis not thread-safe (does not implementSend).
use std::sync::Mutex;
fn main() {
let m = Mutex::new(5);
{
// lock() returns a MutexGuard
let mut num = m.lock().unwrap();
*num = 6;
} // lock is released here
println!("m = {m:?}");
}