Following code is using Mutex to make sure the counter counting correctly.
Just for curiosity, how in Rust can I write it (maybe without Mutex or what ever) using the same (100 or any number) of threads to demonstrate the insistency of threading programming without locks (to demo the counter counting incorrectly)?
use std::sync::{Mutex, Arc};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..100 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
}