Systems Advanced

18  Shared state

To share mutable data across threads you need two things: Arc for shared ownership, and Mutex for exclusive access. Clone the Arc per thread; lock the Mutex to touch the value.

Step 1 / 2

In concurrent_count, have each thread increment a shared counter per_thread times. The final total must be exact -- no lost updates.

Hints
  • let counter = Arc::new(Mutex::new(0usize));, then Arc::clone(&counter) for each thread.
  • let mut n = c.lock().unwrap(); *n += 1; inside the loop.
18_shared_state.rs
Reset to starterCompiled in a sandbox; hidden checks must pass.
Reveal solution
use std::sync::{Arc, Mutex};
use std::thread;

fn concurrent_count(threads: usize, per_thread: usize) -> usize {
    let counter = Arc::new(Mutex::new(0usize));
    let mut handles = Vec::new();
    for _ in 0..threads {
        let c = Arc::clone(&counter);
        handles.push(thread::spawn(move || {
            for _ in 0..per_thread {
                let mut n = c.lock().unwrap();
                *n += 1;
            }
        }));
    }
    for h in handles {
        h.join().unwrap();
    }
    let total = *counter.lock().unwrap();
    total
}