Sub topic 8
Types that are not Sync
This chapter assumes you know that T: Sync means &T is Send, and that you have used thread::spawn and thread::scope. It covers which standard types are not Sync, why, and what to use instead.
What a missing Sync means
A type is Sync when sharing &T across threads is safe. Many threads could then call &self methods at the same time. A type is not Sync when some &self method can mutate or read internal state without synchronization. Two threads calling that method at once would race.
Every non-Sync type in the standard library falls into one of two groups:
- It has interior mutability, meaning it changes through a shared reference, without any lock or atomic operation.
- It has a non-atomic shared count, as in
Rc.
Common non-Sync types
| Type | Send | Sync | Reason |
|---|---|---|---|
| `Cell<T>` | if `T: Send` | no | `set` and `get` through `&self` are unsynchronized |
| `RefCell<T>` | if `T: Send` | no | the borrow flag is a plain integer |
| `Rc<T>` | no | no | the reference count is not atomic |
| `*const T`, `*mut T` | no | no | the compiler opts out by default |
| `mpsc::Receiver<T>` | if `T: Send` | no | the receiving side is for one thread at a time |
| `MutexGuard<T>` | no | if `T: Sync` | the lock must be released on the thread that took it |
Cell and RefCell are Send but not Sync. You can move one to another thread, because only one thread then owns it. You cannot share a reference to it.
Seeing the error
Scoped threads capture variables by reference, so each closure needs &Cell<i32> to be Send. That requires Cell<i32>: Sync.
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. The compiler reports that Cell<i32> cannot be shared between threads safely, and that the trait Sync is not implemented for it. The error says "shared", not "sent". That wording points to Sync rather than Send.
Fixing it
Replace the unsynchronized type with one that is Sync. For a plain counter, an atomic is enough.
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
fn main() {
let hits = AtomicUsize::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));
}This prints 2. Choose the replacement by what you need:
- Use atomics for a single integer, flag, or pointer-sized value.
- Use
Mutex<T>when you need exclusive access to a larger value. It replacesRefCell<T>. - Use
RwLock<T>when reads are frequent and writes are rare. - Use
Arc<T>instead ofRc<T>when ownership is shared.
Checking a type yourself
When you are unsure, ask the compiler with an empty function that has a Sync bound.
use std::cell::{Cell, RefCell};
use std::sync::Mutex;
fn assert_sync<T: Sync>() {}
fn main() {
assert_sync::<Mutex<RefCell<i32>>>();
// assert_sync::<RefCell<i32>>(); // error: RefCell<i32> is not Sync
// assert_sync::<Cell<i32>>(); // error: Cell<i32> is not Sync
}The same rule applies to your own types. A struct is Sync only if every field is. One Cell field makes the whole struct non-Sync.
Exercise
You wrap a counter as Arc<RefCell<i32>> and move a clone into thread::spawn. Which trait does the compiler complain about, and what is the smallest change that fixes it?
Show answer
Send. Arc<T> is Send only when T: Send + Sync, and RefCell<i32> is not Sync. Replace RefCell<i32> with Mutex<i32> to get Arc<Mutex<i32>>.