Sub topic 4
Sync: sharing references between threads
This chapter assumes you know ownership and borrowing, trait bounds, closures with move, and basic use of thread::spawn. It also assumes you know that Send means a value can move to another thread.
What Sync promises
Sync is a marker trait. A type T is Sync if it is safe for several threads to hold &T to the same value at the same time. Send is about moving ownership between threads. Sync is about sharing access while the owner stays where it is.
A shared reference &T normally allows only reads, so many threads reading is fine. The catch is interior mutability. Some types let you change data through &T, such as Cell. If two threads did that at once, you would get a data race. A type is Sync only if every operation available through &T is safe to run concurrently.
Sharing a Sync value
Vec<i32> is Sync, so scoped threads can borrow it. The scope guarantees both threads finish before data is dropped.
use std::thread;
fn main() {
let data = vec![1, 2, 3];
let (sum, len) = thread::scope(|s| {
let a = s.spawn(|| data.iter().sum::<i32>());
let b = s.spawn(|| data.len());
(a.join().unwrap(), b.join().unwrap())
});
println!("sum = {}, len = {}", sum, len);
}This prints sum = 6, len = 3. Each closure captures &data. The compiler accepts that because &Vec<i32> can cross a thread boundary, and that is true exactly when Vec<i32> is Sync.
What happens without Sync
Cell<i32> lets you call set through &Cell<i32>. It has no locking, so it is not Sync.
use std::cell::Cell;
use std::thread;
fn main() {
let counter = Cell::new(0);
thread::scope(|s| {
s.spawn(|| counter.set(counter.get() + 1));
s.spawn(|| counter.set(counter.get() + 1));
});
}This does not compile. The error says that Cell<i32> cannot be shared between threads safely, and that the trait Sync is not implemented for it. The compiler stops the program before two threads can race on counter.
Checking Sync yourself
You can ask the compiler directly with an empty generic function:
use std::sync::Mutex;
fn assert_sync<T: Sync>() {}
fn main() {
assert_sync::<Vec<i32>>();
assert_sync::<Mutex<i32>>();
// assert_sync::<std::cell::Cell<i32>>(); // fails to compile
}Mutex<i32> is Sync even though it allows mutation through &Mutex<i32>. It makes that safe by letting only one thread inside at a time.
Common mistakes
- Assuming "has no
&mutmethods" meansSync. Interior mutability breaks that assumption. - Assuming
Syncmeans "mutable from many threads". It means shared access is safe. Mutation is safe only if the type synchronizes it. - Confusing the two traits. A type can be
Sendbut notSync, likeCell<i32>. You can move it to one thread, but you cannot share it.
Summary of the rule
| Question | Trait needed |
|---|---|
| Can I move `T` into another thread? | `Send` |
| Can several threads hold `&T` at once? | `Sync` |
| Can I share `&Vec<i32>` with a scoped thread? | `Vec<i32>: Sync` |
Exercise
Why is Mutex<i32> Sync while Cell<i32> is not, even though both allow changing the inner value through a shared reference?
Show answer
Mutex<i32> allows only one thread at a time to access the value, because lock blocks other threads, so concurrent use of &Mutex<i32> is safe. Cell<i32> does no synchronization, so two threads calling set through &Cell<i32> could race. Only the Mutex meets the Sync promise.