Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ CONCURRENCY WITH A CONTRACT
BUILD NOTE 43 / 53

Share state with a small critical section.

Separate cross-thread ownership from synchronized mutation.

BY NAVAN SAMI◷ 9 MIN READADVANCEDRUST 2024

01 Understand the contract

Arc<T> provides atomic reference-counted ownership across threads. It does not make arbitrary mutation safe by itself. A Mutex<T> protects access through a guard that unlocks when dropped. Keep the critical section short and avoid slow I/O while holding a synchronous lock. Lock poisoning signals that a thread panicked while holding the lock; decide whether to propagate, recover, or terminate based on the data invariant. In async code, never casually hold a std MutexGuard across await.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/arc-mutex/src/main.rs
use std::{
    sync::{Arc, Mutex},
    thread,
};
fn main() {
    let count = Arc::new(Mutex::new(0_u32));
    let mut workers = Vec::new();
    for _ in 0..4 {
        let count = Arc::clone(&count);
        workers.push(thread::spawn(move || {
            for _ in 0..100 {
                *count.lock().unwrap() += 1;
            }
        }));
    }
    for worker in workers {
        worker.join().unwrap();
    }
    println!("{}", *count.lock().unwrap());
}
↳ EXPECTED OUTPUT
400
  1. 1

    Each Arc clone shares the same mutex-protected counter.

  2. 2

    Every increment holds a short-lived guard.

  3. 3

    Joining all workers makes the final result deterministic.

From the extracted rust-workbench folder
cargo run -p lesson_arc_mutex

03 Mind the boundary

04 Your next build

A SMALL MISSION

Protect a vector with Arc<Mutex<_>>, push one value per worker, sort afterward, and assert all values arrived.

Reveal one possible solution +
solutions/arc-mutex/src/main.rs
use std::{
    sync::{Arc, Mutex},
    thread,
};
fn main() {
    let values = Arc::new(Mutex::new(Vec::new()));
    let jobs: Vec<_> = (0..3)
        .map(|n| {
            let v = Arc::clone(&values);
            thread::spawn(move || v.lock().unwrap().push(n))
        })
        .collect();
    for job in jobs {
        job.join().unwrap();
    }
    let mut result = values.lock().unwrap().clone();
    result.sort();
    assert_eq!(result, [0, 1, 2]);
}

05 Check your reasoning

QUICK SIGNAL CHECK

What protects the mutable payload in Arc<Mutex<T>>?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.