Sub topic 1
Why Sharing Data Across Threads Needs Rules
Prerequisites
This chapter assumes ownership, borrowing, lifetimes, traits, generic bounds, closures, and basic std::thread::spawn usage.
Why sharing data across threads needs rules
A thread is an independent path of execution. If two threads access the same data without rules, their operations can overlap unpredictably. One thread might read while another writes, causing a data race. Rust prevents this by checking thread-safety properties at compile time.
Rust uses two marker traits for these properties. A marker trait communicates a capability without requiring methods.
Send and Sync are marker traits
Send means a value can be moved to another thread. Sync means references to a value can be shared safely between threads.
These traits usually have no methods. The compiler uses their bounds when checking APIs such as thread::spawn.
use std::thread;
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
fn main() {
assert_send::<String>();
assert_sync::<Vec<i32>>();
let message = String::from("hello");
let handle = thread::spawn(move || {
println!("{message}");
});
handle.join().unwrap();
}The move closure takes ownership of message. String is Send, so the compiler permits that transfer.
Send: moving values to another thread
A type is Send when transferring ownership of it to another thread cannot violate its safety rules. Most ordinary owned data is Send. For example, String owns its characters, so one thread can give the whole value to another thread.
Rc<T> is an important exception. Its reference count is not atomic, so simultaneous updates from different threads could corrupt it. Therefore, Rc<T> is not Send. Use a thread-safe alternative when ownership must cross threads.
Sync: sharing references between threads
A type is Sync when multiple threads can safely hold references to it at the same time. Immutable references are safe to share only when the referenced type supports concurrent access.
For example, i32 is Sync: reading the same integer through shared references causes no conflict. Types with unsynchronized interior mutation, such as Cell<T>, are not generally Sync.
How Sync is defined in terms of Send
Rust defines the relationship precisely:
T: Sync exactly when &T: Send.
If a shared reference can move safely between threads, then several threads may hold such references safely. This definition connects the two traits without making them identical.
Exercise
What does T: Sync guarantee, and how is it related to Send?
Show answer
It guarantees that &T can move safely between threads. Rust defines T: Sync exactly when &T: Send.