Sub topic 4
Sync: sharing references between threads
This chapter covers the Sync trait. It assumes you know ownership, borrowing and lifetimes, traits and trait bounds, closures with move, and the basics of std::thread::spawn and JoinHandle. The previous chapter covered Send, which is about moving a value to another thread. Sync is about a different question: may several threads look at the same value at once?
What Sync promises
Sync is a marker trait. It has no methods. Implementing it is a promise about a type T: it is safe for many threads to hold &T to the same value at the same time.
Safe here means free of data races. A data race happens when two threads access the same memory at the same time, at least one access is a write, and nothing orders the accesses. In Rust, a shared reference &T normally permits only reads. That makes sharing look harmless. The catch is interior mutability. Types such as Cell<T> and RefCell<T> let you change a value through a &T. If two threads each hold a &Cell<i32> and both call set, the writes race.
So Sync separates two kinds of types:
- Types where
&Tcan only read, or where mutation through&Tis synchronized. These areSync. - Types where
&Tcan mutate without synchronization. These are notSync.
The rule behind it
The standard library defines Sync through Send:
T is Sync exactly when &T is Send.
Sending a &T to another thread is the same act as sharing T with that thread. The other thread holds a reference to your data. So the compiler asks whether the reference itself may cross the thread boundary, and that question is answered by Send on &T.
The next chapter looks at this equivalence in detail. For now, use it as a way to reason: to ask "is T Sync?", ask "may I hand a &T to another thread?"
Which types are Sync
Most plain data is Sync. Integers, bool, String, Vec<i32> and tuples or structs made of such types are all Sync, because reading them from many threads at once is safe.
A few types are deliberately not Sync:
| Type | Sync? | Reason |
|---|---|---|
| `i32`, `String`, `Vec<i32>` | Yes | Shared access is read-only. |
| `Cell<i32>` | No | `set` mutates through `&self` without synchronization. |
| `RefCell<i32>` | No | Its borrow flag is a plain counter, not atomic. |
| `Rc<i32>` | No | Cloning through `&Rc` updates a non-atomic count. |
| `Mutex<i32>` | Yes | `lock` serializes all access. |
| `AtomicUsize` | Yes | Every operation is atomic. |
| `*const T`, `*mut T` | No | The compiler cannot reason about what they point to. |
Mutex<T> is worth noticing. Mutex<T> is Sync whenever T is Send. It does not require T: Sync. The reason is that the mutex lets only one thread at a time touch the inner value, so the value is never accessed by two threads at once. It only has to be movable between threads, which is what Send means.
Asking the compiler
You can test a type directly. Write empty generic functions with a trait bound. A call compiles only if the type satisfies the bound.
use std::cell::Cell;
use std::rc::Rc;
use std::sync::Mutex;
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
fn main() {
assert_send::<String>();
assert_sync::<Vec<i32>>();
assert_send::<Cell<i32>>();
assert_sync::<Mutex<i32>>();
// Each of these lines would fail to compile if uncommented:
// assert_send::<Rc<i32>>();
// assert_sync::<Cell<i32>>();
}Cell<i32> is Send but not Sync. That combination shows that the two traits are independent. You may move a Cell to another thread, because then only one thread owns it. You may not share &Cell between threads, because both could call set.
Sync in action: scoped threads
Ordinary thread::spawn needs data that lives for 'static, so you cannot borrow local variables. Scoped threads remove that limit. A scope guarantees every thread inside it finishes before the scope returns, so the threads can borrow locals.
Each spawned closure borrows data as &Vec<i32>. Two threads hold that reference at once, so Vec<i32> must be Sync.
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. No Arc is needed. The borrow checker knows the scope ends before data does, and Sync tells it that sharing the reference is safe.
How Sync appears in a failing build
Suppose you try to share a Cell between scoped threads:
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 compiler reports that Cell<i32> cannot be shared between threads safely, and that the trait Sync is not implemented for it. It also explains that &Cell<i32> therefore cannot be sent between threads, which is the Send-on-reference rule at work.
To fix it, choose a type whose shared access is synchronized:
use std::sync::atomic::{AtomicI32, Ordering};
use std::thread;
fn main() {
let counter = AtomicI32::new(0);
thread::scope(|s| {
s.spawn(|| counter.fetch_add(1, Ordering::SeqCst));
s.spawn(|| counter.fetch_add(1, Ordering::SeqCst));
});
println!("{}", counter.load(Ordering::SeqCst));
}This prints 2. Use Mutex<T> instead when the data is not a single integer.
Common mistakes
- Confusing
SyncwithSend.Sendmoves ownership.Syncshares a reference. A type can have either one without the other. - Assuming that a
Synctype may be mutated freely.Synconly says that&Tis safe to share. Mutation still needs&mut Tor interior mutability that is synchronized. - Expecting
Mutex<T>to needT: Sync. It needsT: Send. - Adding
Arcto a non-Synctype and hoping it works.Arc<T>isSendandSynconly whenTis bothSendandSync.Arc<Cell<i32>>is rejected for exactly this reason. Wrap the value in aMutexinstead.
Where the compiler gets Sync from
You rarely write impl Sync. Sync is an auto trait: the compiler implements it for a struct if every field is Sync. One non-Sync field, such as a Cell, makes the whole struct non-Sync. A later chapter covers this derivation and the rare cases where you write an unsafe impl by hand.
Summary of the working model
Syncmeans&Tis safe to use from several threads.T: Syncis the same as&T: Send.- Read-only data is
Sync. Unsynchronized interior mutability is not. - Scoped threads show
Syncdirectly: they share borrowed data withoutArc. - When the compiler says a type is not
Sync, replace unsynchronized interior mutability withMutex,RwLockor an atomic.
Exercise
A struct Config has two fields: name: String and hits: Cell<u32>. You want two scoped threads to borrow &Config. Does it compile? If not, give one change that fixes it, and say whether Config is still Send after your change.
Show answer
It does not compile. Cell<u32> is not Sync, so Config is not Sync, and two threads cannot hold &Config at once. Change hits to AtomicU32 (or Mutex<u32>). Both are Sync, so Config becomes Sync. Config was already Send, since String and Cell<u32> are both Send, and it stays Send after the change.
Exercise
Mutex<T> is Sync when T: Send. Explain in one or two sentences why T: Sync is not required.
Show answer
The mutex lets only one thread access the inner value at a time, so the value is never used by two threads simultaneously. The value only needs to be safe to move between threads, which is Send.