Sub topic 2
Why sharing mutable data between threads is a problem
This chapter assumes you know Rust ownership and borrowing, closures and move, and how to call thread::spawn and join. It explains why the obvious ways of sharing a counter between threads fail. The rest of the tutorial builds the fix.
The lost update
The statement counter += 1 looks like one step, but the CPU runs it as three: read the value, add one, write the result back. Two threads can interleave those steps.
Both threads did their work, but the counter went from 5 to 6 instead of 7. This is a data race. A data race happens when two or more threads access the same memory at the same time, at least one of them writes, and nothing coordinates them. In C and C++ a data race is undefined behavior. Rust's compiler rejects it in safe code.
Attempt 1: borrow the variable
The first idea is to let the thread borrow a local variable.
use std::thread;
fn main() {
let mut counter = 0;
// Does not compile: closure may outlive the current function (E0373).
let handle = thread::spawn(|| {
counter += 1;
});
handle.join().unwrap();
}thread::spawn requires the closure to be 'static. The compiler cannot prove that the new thread ends before counter goes out of scope, so it refuses the borrow. This check stops a thread from using a dead stack variable.
Attempt 2: move the variable
Adding move makes the code compile, but it does not do what you want.
use std::thread;
fn main() {
let mut counter = 0;
let handle = thread::spawn(move || {
counter += 1;
println!("inside thread: {}", counter);
});
handle.join().unwrap();
println!("in main: {}", counter);
}This prints inside thread: 1 and then in main: 0. An i32 implements Copy, so move gives the closure its own copy. The thread increments that copy and the original stays at 0. There is no shared state here. Rust may warn that the mut binding is not needed for the final println!, but the program is valid.
What the compiler is protecting you from
Each failed attempt shows one rule Rust enforces:
| Approach | Result | Rule enforced |
|---|---|---|
| Borrow with `&mut` | Compile error | A borrow cannot outlive its owner |
| `move` a `Copy` value | Compiles, no sharing | Each thread owns its own copy |
| `move` a non-`Copy` value | Compiles, one owner | Only one owner exists at a time |
Rust's aliasing rule says a value can have many readers or one writer, never both. Threads would break this rule if several could write at once, so safe Rust has no direct way to share a mutable value across threads.
What you need instead
Sharing mutable state across threads needs two separate tools:
- Shared ownership, so that several threads can keep the value alive.
Arcprovides this. - Controlled access, so that only one thread changes the value at a time.
Mutexprovides this.
The next chapters introduce each one, then combine them.
Exercise
A student writes let mut total = 0; and spawns four threads with move closures that each run total += 10. After joining all four, total in main is still 0, and the program compiles without errors. Why is there no data race, and why is the result still wrong for the student's goal?
Show answer
total is an i32, which is Copy, so each move closure receives its own copy. Each thread changes only its private copy, so no memory is shared and no data race can occur. The goal was a shared total, and that requires shared ownership with synchronized access (Arc<Mutex<i32>>).