Systems Advanced
20 Atomics
For a simple shared number a Mutex is heavier than you need. Atomics update in one indivisible hardware step: redo the counter lock-free, then track a maximum with fetch_max.
In concurrent_max, every thread reports its value with fetch_max; return the final maximum.
Hints
- One thread per value; each calls
fetch_max(v, Ordering::Relaxed)on the shared atomic. - Start the atomic at 0 and the empty-input case falls out for free.
Reveal solution
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
fn concurrent_max(values: Vec<usize>) -> usize {
let max = Arc::new(AtomicUsize::new(0));
let mut handles = Vec::new();
for v in values {
let m = Arc::clone(&max);
handles.push(thread::spawn(move || {
m.fetch_max(v, Ordering::Relaxed);
}));
}
for h in handles {
h.join().unwrap();
}
max.load(Ordering::Relaxed)
}