Sub topic 1
Shared State in Rust with `Arc` and `Mutex`
Prerequisites
This chapter assumes Rust ownership, borrowing, lifetimes, closures, move, Result, and basic use of std::thread::spawn.
Threads and `move` Closures
thread::spawn runs a closure on a new thread. A move closure takes ownership of the values it captures. This matters because the original thread might finish or change its stack before the new thread uses those values.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = Vec::new();
for _ in 0..2 {
let counter = Arc::clone(&counter);
handles.push(thread::spawn(move || {
for _ in 0..1_000 {
let mut value = counter.lock().unwrap();
*value += 1;
}
}));
}
for handle in handles {
handle.join().unwrap();
}
println!("{}", *counter.lock().unwrap());
}The program prints 2000. Each thread owns a clone of the Arc, and both threads access the same protected integer.
Why Shared Mutable Data Is a Problem
If two threads mutate the same value without coordination, their operations can overlap. For example, incrementing a counter usually means reading, adding one, and writing. Two threads can read the same old value and lose one update. This is a data race.
Rust prevents many data races at compile time. A normal mutable reference cannot be shared between threads, because only one mutable reference may exist at a time. For safe shared mutation, use a type that coordinates access.
`Arc`: Shared Ownership Across Threads
Arc<T> is an atomically reference-counted pointer. It lets multiple threads own the same allocation. Arc::clone creates another ownership handle; it does not copy the underlying data.
Arc provides ownership, not mutable access. The Mutex in Arc<Mutex<T>> provides that coordination.
`Send` and `Sync`
Send means a value can move safely to another thread. Sync means references to a value can be shared safely between threads.
Rc<T> is not thread-safe, so the compiler rejects Rc<Mutex<T>> in thread::spawn. Its reference count is not atomic. Arc<T> uses atomic reference counting and is designed for this use case. The compiler checks these marker traits before allowing captured values into a thread.
`Mutex`: One Thread at a Time
Mutex<T> provides mutual exclusion. Calling lock waits until no other thread holds the lock and returns a MutexGuard<T>. The guard provides access to the value. When the guard leaves scope, Rust drops it and unlocks the mutex.
Keep the guarded section small. Do slow work before locking or after the guard is dropped.
Exercise
What does Arc provide, and what does Mutex provide?
Show answer
Arc provides shared ownership across threads. Mutex allows only one thread at a time to access the protected value.