Module 7Mutex & Interior MutabilityLesson 4 of 722 min
Mutex + Arc
Shared Vec of samples across threads.
Arc<Mutex<T>>
rust
use std::sync::{Arc, Mutex};
let data = Arc::new(Mutex::new(Vec::new()));Lock scope
Keep critical sections short — do not hold locks while doing heavy RNG if avoidable.
Poisoning
If a thread panics while holding the lock, lock() returns Err.
Challenge
Also maintain a shared running sum in Mutex<f64>.
Tips
- Short critical sections
- Prefer channels when possible
- rayon offline for data-parallel
Try it live
Mutex + ArcRust 2021
Loading editor…
Output
Press Run to compile and execute.