Add parking_lot to your Cargo.toml and replace std::sync::Mutex with parking_lot::Mutex to reduce lock contention and improve throughput.
[dependencies]
parking_lot = "0.12"
use parking_lot::Mutex;
fn main() {
let counter = Mutex::new(0);
let mut handles = vec![];
for _ in 0..10 {
let counter = counter.clone();
let handle = std::thread::spawn(move || {
let mut num = counter.lock();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock());
}