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 2 / 2

In collect_squares, each of n threads pushes i * i into a shared vec. Return the values sorted ascending.

Hints
  • Share a Arc<Mutex<Vec<usize>>>; lock it to push.
  • After joining, clone the vec out and sort() it (threads finish in any order).
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 collect_squares(n: usize) -> Vec<usize> {
    let out = Arc::new(Mutex::new(Vec::new()));
    let mut handles = Vec::new();
    for i in 0..n {
        let out = Arc::clone(&out);
        handles.push(thread::spawn(move || {
            out.lock().unwrap().push(i * i);
        }));
    }
    for h in handles {
        h.join().unwrap();
    }
    let mut v = out.lock().unwrap().clone();
    v.sort();
    v
}