Sub topic 1
Why Sharing Data Across Threads Needs Rules
Prerequisites
This chapter assumes you already know:
- Ownership, borrowing and lifetimes in Rust.
- Traits, trait bounds and generics.
- Closures and the
movekeyword. - Basic use of
std::thread::spawnandJoinHandle.
The problem: data races
A data race happens when two or more threads access the same memory at the same time, at least one access is a write, and nothing orders the accesses. The result is undefined behavior. You may see torn values, lost updates or crashes that appear only under load.
Most languages leave this to the programmer. You use locks by convention and hope that every code path remembers them. Rust moves the check into the compiler. Its aim is that safe code cannot contain a data race.
Rust's rules already cover half of the problem
Ownership and borrowing already forbid the dangerous pattern on a single thread. At any moment, a value has either many shared references (&T) or one mutable reference (&mut T). That is the same condition that data races need to break: shared and mutable at once.
Threads add a new question. A type that is safe to use from one thread may not be safe once a second thread can reach it. For example, Rc<T> updates its reference count with plain, non-atomic operations. Two threads cloning the same Rc could corrupt the count, and the value could be freed too early or never.
So the compiler needs to know two facts about every type:
- Can I move a value of this type to another thread?
- Can two threads hold references to the same value at once?
Rust answers these with two traits, Send and Sync. This chapter only motivates them. The next chapters define each in detail.
Where the check happens
The check sits on the functions that start threads. Here is the signature of thread::spawn, shortened:
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,The closure F must be Send, because it moves to a new thread. Its return value T must be Send, because it travels back through join. If the closure captures something that is not safe to move, the program does not compile.
A program that the compiler accepts
This program shares a counter between four threads. The shared state is safe, so it compiles and prints 4.
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..4 {
let counter = Arc::clone(&counter);
handles.push(thread::spawn(move || {
*counter.lock().unwrap() += 1;
}));
}
for handle in handles {
handle.join().unwrap();
}
println!("{}", *counter.lock().unwrap());
}A program that the compiler rejects
Swap Arc for Rc in a simple example and the program no longer compiles.
use std::rc::Rc;
use std::thread;
fn main() {
let data = Rc::new(5);
let handle = thread::spawn(move || {
println!("{}", data);
});
handle.join().unwrap();
}The compiler reports that Rc<i32> cannot be sent between threads safely. Nothing was run and no thread was started. The mistake was caught from the types alone.
What comes next
The following chapters build the model step by step. They cover what the marker traits are, what Send and Sync each promise, how the compiler derives them, and which standard types opt out.
Exercise
In the Rc example, what makes the compiler reject the program, and why is the check done on thread::spawn rather than on Rc itself?
Show answer
The closure passed to thread::spawn must be Send, and it captures an Rc<i32>, which is not Send because its reference count is not atomic. The check sits on spawn because Rc is perfectly fine on a single thread. It only becomes a problem when a value crosses to another thread, and spawn is where that happens.