Sub topic 1
Why Sharing Data Across Threads Needs Rules
Threads let a program do several things at once, but they also let two pieces of code touch the same memory at the same moment. This chapter explains why that is dangerous and what problem Rust's thread-safety rules solve. It also shows which compile errors you meet first when you start using threads. The traits Send and Sync are introduced only as a preview here. The following chapters cover them in detail.
Prerequisites
This chapter assumes you already know:
- Ownership, borrowing and lifetimes: a value has one owner, and you can have many shared references (
&T) or one mutable reference (&mut T), but not both at once. - Traits, trait bounds and generics, enough to read a signature like
fn spawn<F: FnOnce() + Send + 'static>(f: F). - Closures and the
movekeyword. - Basic use of
std::thread::spawnandJoinHandle::join.
The problem: two threads, one piece of memory
Each thread in a process has its own stack, but all threads share the same heap and the same statics. If two threads can reach the same memory, their operations can interleave in ways you did not plan for.
Take a counter and the statement counter += 1. The CPU does not run it as one step. It runs three:
- Read the current value.
- Add one.
- Write the result back.
If two threads run those steps at the same time, they can overlap:
Both threads ran correctly in isolation. The bug comes from the interleaving. This is called a lost update.
What a data race is
A data race happens when all three of these are true:
- Two or more threads access the same memory location.
- At least one of the accesses is a write.
- Nothing orders the accesses, such as a lock or an atomic operation.
In C and C++, a data race is undefined behavior. The program is not just wrong in a predictable way. The compiler is allowed to assume races never happen, so optimizations can turn a race into corrupted data, crashes, or results that change between runs and between machines. These bugs are also hard to reproduce, because they depend on timing.
A data race is not the same thing as a race condition. A race condition is a logic bug where the result depends on timing, such as two threads competing to create the same file. Rust does not prevent race conditions in general. It prevents data races.
| Term | Meaning | Does safe Rust prevent it? |
|---|---|---|
| Data race | Unsynchronized concurrent access to one memory location, with at least one write | Yes |
| Race condition | Program result depends on the timing of events | No |
| Deadlock | Threads wait on each other forever | No |
How Rust approaches the problem
Many languages leave it to the programmer to remember to lock. Others, like Python, add a global lock that limits parallelism. Rust moves the check to compile time.
Rust already has the main idea. Its borrowing rules say that at any moment a value has either many readers or one writer, never both. A data race needs a writer and another access at the same time, so the borrow rules already forbid it within one thread. The remaining question is how to apply those rules when values cross thread boundaries.
The compiler needs answers to two questions about any type T:
- Is it safe to move a value of type
Tto another thread, so that thread becomes its owner? - Is it safe for several threads to hold
&Tat the same time?
Rust encodes these answers as two traits. The first is Send and the second is Sync. They have no methods. They are labels the compiler checks. APIs such as thread::spawn demand the right label in their signatures, so a type that is unsafe to share cannot be passed in. The next chapters explain both traits fully.
The first errors you meet
Most programmers see the rules before they ever see the words Send or Sync. The first error comes from borrowing a local variable in a spawned thread:
use std::thread;
fn main() {
let numbers = vec![1, 2, 3];
let handle = thread::spawn(|| {
println!("{:?}", numbers);
});
handle.join().unwrap();
}This does not compile. The compiler reports error E0373: the closure may outlive the current function, but it borrows numbers. The reason is that a spawned thread can keep running after main has returned and dropped numbers. The reference would then dangle. The compiler cannot see that you call join a few lines later, because spawn makes no promise about when the thread ends.
One fix is to move ownership into the closure:
use std::thread;
fn main() {
let numbers = vec![1, 2, 3];
let handle = thread::spawn(move || {
println!("{:?}", numbers);
});
handle.join().unwrap();
}This prints [1, 2, 3]. The new thread owns the vector, so nothing can free it from under the thread. The cost is that main can no longer use numbers.
That leads to the real question. What if several threads need the same data, and some need to change it? Handing the value to one thread is not enough. You need a way to share it, and the type of the shared thing decides whether sharing is safe. This is where the Send and Sync labels do their work.
A preview of the safe version
Here is a working shared counter. Do not worry about every detail yet. The point is that the compiler accepts it because every type involved is allowed to cross threads:
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());
}It prints 4. Compare it to the lost update diagram. The Mutex forces the read, add and write steps of one thread to finish before another thread's steps start. The Arc lets four threads own the same mutex, and its reference count is updated atomically. If you replaced Arc with Rc, the program would no longer compile. Rc updates its count with ordinary, non-atomic operations, and two threads doing that can corrupt the count. The compiler stops you because Rc lacks the Send label.
Why the rules live in the type system
Putting these checks in types has practical consequences:
- The check is free at run time. There is no flag or lock added to find races. The compiler rejects the program instead.
- The check is checked everywhere. A library author labels a type once, and every user of that type is covered.
- The rules compose. A struct is safe to send if all its fields are, so most types get the right answer without any code from you.
- The rules can be wrong only in
unsafecode. If you writeunsafe impl Sendfor a type that is not safe to send, the compiler trusts you. A later chapter covers when that is justified.
The rules also have limits. They do not stop deadlocks, they do not stop logic races, and they do not check how you order atomic operations. They guarantee one thing: safe Rust code cannot produce a data race.
Summary of the chapter's ideas
- Threads share memory, so unordered reads and writes can corrupt data.
- A data race needs concurrent access, at least one write, and no synchronization. It is undefined behavior in languages without a checker.
- Rust's borrowing rules already prevent races inside one thread.
SendandSyncextend them across threads. - The first errors you see are lifetime errors from
thread::spawn, and the usual fix ismoveor shared ownership.
Exercise
Two threads each run counter += 1 on the same i32 with no synchronization, and the final value is 1 instead of 2. Name the problem, and say which of the three conditions of a data race would no longer hold if both threads locked a Mutex around the increment.
Show answer
The problem is a data race that causes a lost update, because both threads read 0 before either writes. A Mutex removes the third condition, that nothing orders the accesses. The lock makes one thread's read, add and write finish before the other thread's begin, so the final value is 2.
Exercise
A spawned closure uses println!("{:?}", numbers) where numbers is a local Vec<i32>, without move. Why does the compiler reject it even though main calls join afterward, and what are two ways to make it compile?
Show answer
thread::spawn accepts closures that must not borrow from the caller's stack, because the thread may outlive the function, and the compiler does not use your join call to prove otherwise. You can add move so the thread owns the vector, or you can use thread::scope, which guarantees threads finish before the scope ends and so lets them borrow locals.