use std::thread;
use std::sync::{Arc,Mutex};
use std::time::Duration;
use rand::Rng;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut threads = vec![];
for i in 1..10 {
let cloned_counter = Arc::clone(&counter);
let th = thread::spawn(move || {
let mut num = cloned_counter.lock().unwrap();
let mut rng = rand::thread_rng();
thread::sleep(Duration::from_millis(rng.gen::<u64>() % 100));
*num += i;
println!("=> {}: {}", i, *num);
});
threads.push(th);
}
for th in threads {
th.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
}