Sub topic 8
Types that are not Sync
This chapter assumes you know what Send and Sync promise, that T: Sync means &T: Send, and that auto traits derive from fields. It covers which standard types are not Sync, why, and how to fix the errors they cause.
What "not Sync" means
A type T is Sync when it is safe for several threads to hold &T at the same time. Sharing a reference means any of those threads can call any &self method. So a type is not Sync when some &self method can change state without synchronization.
Rust calls this interior mutability: mutation through a shared reference. Ordinary &T is read-only, so it is always safe to share. Interior mutability breaks that guarantee, and each interior-mutability type must either synchronize the mutation or opt out of Sync.
The types in this chapter opt out. They mutate through &self with plain, non-atomic operations.
The common non-Sync types
| Type | Send | Sync | Reason |
|---|---|---|---|
| `Cell<T>` | if `T: Send` | no | `set` and `get` through `&self` are plain reads and writes |
| `RefCell<T>` | if `T: Send` | no | the borrow flag is a plain integer |
| `UnsafeCell<T>` | if `T: Send` | no | the base primitive for all interior mutability |
| `Rc<T>` | no | no | the reference count is not atomic |
| `*const T`, `*mut T` | no | no | the compiler assumes nothing about raw pointers |
| `mpsc::Receiver<T>` | if `T: Send` | no | receiving is meant for one consumer at a time |
| `std::cell::OnceCell<T>` | if `T: Send` | no | lazy initialization is not synchronized |
| `MutexGuard<'_, T>` | no | if `T: Sync` | the lock must be released on the thread that took it |
Two rows are worth a closer look.
MutexGuard is the reverse of the usual pattern. It is Sync but not Send, because some operating systems require the thread that locked a mutex to be the one that unlocks it.
Receiver<T> is Send but not Sync. You can move it to a consumer thread, but two threads cannot hold &Receiver at once. Sender<T> has been Sync since Rust 1.72, so one sender can be shared by reference.
Why Cell is not Sync
Take a counter that two threads increment through a shared reference:
use std::cell::Cell;
use std::thread;
fn main() {
let hits = Cell::new(0);
thread::scope(|s| {
s.spawn(|| hits.set(hits.get() + 1));
s.spawn(|| hits.set(hits.get() + 1));
});
}This does not compile. Each closure captures &hits, and a spawned closure must be Send. A closure holding &Cell<i32> is Send only if &Cell<i32> is Send. That holds only if Cell<i32>: Sync, which it is not. The compiler reports that Cell<i32> cannot be shared between threads safely and that the trait Sync is not implemented for it.
Without that check, both threads could read 0 and both write 1, losing an update. That is a data race.
For a counter, the fix is an atomic type. Atomics are Sync because every operation is indivisible:
use std::sync::atomic::{AtomicI32, Ordering};
use std::thread;
fn main() {
let hits = AtomicI32::new(0);
thread::scope(|s| {
s.spawn(|| hits.fetch_add(1, Ordering::Relaxed));
s.spawn(|| hits.fetch_add(1, Ordering::Relaxed));
});
println!("{}", hits.load(Ordering::Relaxed));
}The program prints 2. The scope guarantees both threads finish before the final load.
Why RefCell is not Sync
RefCell checks borrow rules at run time. It keeps a counter of active borrows and panics if you ask for borrow_mut while another borrow is live. That check is correct only if the counter is updated safely.
The counter is a plain integer. Two threads could both see "no active borrows" and both receive a &mut. The run-time check would then fail to catch aliased mutable access, which is the exact bug RefCell exists to catch. So RefCell<T> is not Sync.
The fix is a Mutex<T> or RwLock<T>. They enforce the same "one writer or many readers" rule, but they block or wait across threads instead of panicking.
Not Sync does not mean not Send
Cell and RefCell are Send when their contents are. Moving a value to another thread means one thread owns it at a time. No two threads ever hold references at once, so the unsynchronized mutation never races.
use std::cell::RefCell;
use std::thread;
fn main() {
let log = RefCell::new(Vec::new());
let handle = thread::spawn(move || {
log.borrow_mut().push("worker");
log.into_inner()
});
println!("{:?}", handle.join().unwrap());
}The program prints ["worker"]. The RefCell moves into the thread, the thread uses it alone, and the result moves back through join.
This is often the simplest fix. If only one thread needs the value at a time, move it. Reach for a Mutex only when several threads need access at once.
How the property spreads
Sync is an auto trait. A struct is Sync only if every field is Sync. One non-Sync field makes the whole struct non-Sync, however deeply it is nested.
The compiler can check this for you with the empty-function trick:
use std::cell::{Cell, RefCell};
use std::sync::mpsc::{Receiver, Sender};
use std::sync::{Mutex, RwLock};
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
#[allow(dead_code)]
struct Stats {
name: String,
hits: Cell<u32>,
}
fn main() {
assert_send::<Stats>();
assert_send::<RefCell<Vec<i32>>>();
assert_send::<Receiver<i32>>();
assert_sync::<Sender<i32>>();
assert_sync::<RwLock<i32>>();
assert_sync::<Mutex<Cell<i32>>>();
// Each of these lines would fail to compile if uncommented:
// assert_sync::<Stats>();
// assert_sync::<Receiver<i32>>();
}Stats is Send but not Sync, because of its one Cell field. The String field is Sync, but that does not matter.
The last assertion is surprising. Mutex<Cell<i32>> is Sync even though Cell<i32> is not. This is deliberate, and the next section explains it.
Wrappers can restore Sync
A lock turns "unsynchronized access to T" into "one thread at a time". The standard library encodes this in the bounds on its impls:
Mutex<T>isSyncwhenT: Send. It does not needT: Sync, because only one thread has access to the inner value at any moment.RwLock<T>isSynconly whenT: Send + Sync. Many readers can hold&Tat once, soTitself must tolerate shared references.- Atomic types such as
AtomicUsizeandAtomicBoolareSyncunconditionally. OnceLock<T>is the thread-safe counterpart ofOnceCell<T>. It isSyncwhenT: Send + Sync.
So RwLock<Cell<i32>> is not Sync, while Mutex<Cell<i32>> is. When a Mutex is the only way to reach the value, a Cell inside it is safe. In practice you would use a plain i32 inside the Mutex, because the lock already provides the mutation. The example only shows how the bounds work.
Choosing a fix
Reading the error
Errors about Sync usually name the closure, not the type you wrote. A typical one says that RefCell<Vec<i32>> cannot be shared between threads safely, then adds that the trait bound Sync is not satisfied. It often finishes with a note that required for &RefCell<Vec<i32>> to implement Send.
Read it from the bottom up. The last note shows the chain of requirements: the spawn needs Send, the closure captures a reference, and a reference is Send only if its target is Sync.
Summary
Types become non-Sync because they mutate through &self without synchronization. Cell, RefCell, UnsafeCell, OnceCell, raw pointers, Rc, and Receiver are the usual cases. The property spreads to any struct that contains them. You can fix it by moving the value to one thread, by using an atomic, or by wrapping the value in a Mutex or RwLock.
Exercise
A struct has fields id: u64 and cache: RefCell<Vec<String>>. Is it Send? Is it Sync? Name two ways to let several threads read and update the cache at the same time.
Show answer
It is Send, because u64 and RefCell<Vec<String>> are both Send (Vec<String> is Send). It is not Sync, because RefCell is not Sync, and one non-Sync field makes the whole struct non-Sync. To share it across threads, replace RefCell with Mutex (so the field is Mutex<Vec<String>>), or with RwLock if reads are frequent. Wrapping the whole struct in Arc<Mutex<...>> also works.
Exercise
Why is Mutex<Cell<i32>> Sync, while RwLock<Cell<i32>> is not?
Show answer
Mutex<T> is Sync when T: Send, because the lock lets only one thread touch the inner value at a time, and Cell<i32> is Send. RwLock<T> allows many threads to hold &T simultaneously, so it requires T: Send + Sync. Cell<i32> is not Sync, so RwLock<Cell<i32>> is not Sync.