use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
use std::time::Instant;
let now = Instant::now();
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
for _ in 0..1000 {
thread::sleep(Duration::from_millis(1));
*num += 1;
}
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
let elapsed = now.elapsed();
println!("Elapsed: {:.2?}", elapsed);
}
let handle = thread::spawn(move || {
for _ in 0..1000 {
thread::sleep(Duration::from_millis(1));
let mut num = counter.lock().unwrap();
*num += 1;
}
});