Rust's standard library has support for mutexes which allow us to lock and unlock access to a given piece of memory.
use std::sync::Mutex;
fn main() {
let m = Mutex::new(5);
{
let mut num = m.lock().unwrap();
*num = 6;
}
println!("m = {m:?}");
}
Generally, with mutexes you need to remember to "lock the mutex" before accessing data and then remember to "unlock" it after you're done using the data. Rust is quite helpful in ensuring we do this correctly at compile time.
In this example we cannot access the underlying value without locking the mutex,
solving the first problem. The second issue, of unlocking it when we're done, is
solved because the returned MutexGuard type (which we called unwrap on)
inplements Drop to automatically release the lock when it goes out of scope.