Loading RustViz Engine...
Share and increment an atomic counter concurrently across multiple OS threads.
This problem is currently in blueprint template mode. Once the concept foundation is finalized, live in-browser WebAssembly compilation and test assertion runners will be enabled here.
use std::sync::{Arc, Mutex};
use std::thread;
pub fn parallel_sum(tasks: usize) -> i32 {
let counter = Arc::new(Mutex::new(0));
let mut handles = Vec::new();
for _ in 0..tasks {
let c = Arc::clone(&counter);
handles.push(thread::spawn(move || {
let mut num = c.lock().unwrap();
*num += 1;
}));
}
for h in handles { h.join().unwrap(); }
let res = *counter.lock().unwrap();
res
}