If there is a need to share the data across multiple #threads, 202112061109# will inevitably happen. The need for a mutex (mutual exclusion lock) arises, so that only the one that obtained the lock can modify the data state at a time, where others will queue up and wait for the lock to be released. Rust provides Mutex
type through the standard library std::sync::Mutex
. Acquiring the lock from Mutex
can be done by simply calling the function lock
. However, there is a need to handle the error that could arise if the current owner of the mutex panics during its execution.
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 1..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
}
for handle in handles {
handle.join().unwrap();
}
println!("counter: {}", *counter.lock().unwrap()); // Outupt: counter: 10
As you can see that, we wrap around the Mutex into another type, Arc
(imported from std::sync::Arc
). It allows the data to be shared across multiple threads without violating the rule of Rust ownership, that is, it is atomic. You can treat it as 202206221720# with the 202207172159# and 202207172210# 202204061235#.
Further inspection into the code, we find out that Mutex offer interior mutability, and can be 202206221604# using the syntax *
. It is essentially the same to the 202206232210#. Therefore, one advice is to treat Mutex as if it is a 202111301656# with 202207172210# 202204061235#.