Concurrency Building Blocks
Mutex Counter
Lock Before Updating
Mutex protects shared data by requiring a lock before code can read or change the value.
Program
Play the program to choose the increment added while the counter is locked.
mutex_counter.rs
use std::sync::Mutex;
fn main() {
let increment = ;
let counter = Mutex::new(10);
{
let mut value = counter.lock().unwrap();
*value += increment;
}
let total = *counter.lock().unwrap();
println!("total={total}");
}
use std::sync::Mutex;
fn main() {
let increment = ;
let counter = Mutex::new(10);
{
let mut value = counter.lock().unwrap();
*value += increment;
}
let total = *counter.lock().unwrap();
println!("total={total}");
}
use std::sync::Mutex;
fn main() {
let increment = ;
let counter = Mutex::new(10);
{
let mut value = counter.lock().unwrap();
*value += increment;
}
let total = *counter.lock().unwrap();
println!("total={total}");
}
Mutex
`Mutex::new` wraps data that should be updated through a lock.
lock
`lock().unwrap()` returns a guard that grants access while it is in scope.
scope
The inner block releases the first lock before the final read.