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.

Step 1 / 2

Redo concurrent_count without a Mutex: an AtomicUsize and fetch_add.

Hints
  • AtomicUsize::new(0) inside an Arc, cloned per thread -- same shape as the Mutex version.
  • c.fetch_add(1, Ordering::Relaxed) increments; counter.load(Ordering::Relaxed) reads at the end.
20_atomics.rs
Reset to starterCompiled in a sandbox; hidden checks must pass.
Reveal solution
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;

fn concurrent_count(threads: usize, per_thread: usize) -> usize {
    let counter = Arc::new(AtomicUsize::new(0));
    let mut handles = Vec::new();
    for _ in 0..threads {
        let c = Arc::clone(&counter);
        handles.push(thread::spawn(move || {
            for _ in 0..per_thread {
                c.fetch_add(1, Ordering::Relaxed);
            }
        }));
    }
    for h in handles {
        h.join().unwrap();
    }
    counter.load(Ordering::Relaxed)
}