Sub topic 5
How Sync is defined in terms of Send
This chapter assumes you know the following:
- What
SendandSynceach promise. - That they are auto traits.
- How
thread::spawnand closures withmovework. - How shared references (
&T) differ from mutable references (&mut T).
Here you will see the single rule that ties the two traits together, and you will use it to predict compiler behavior without trial and error.
The rule
The standard library defines Sync through Send:
T: Sync exactly when &T: SendRead it in both directions:
- If
&Tcan be moved to another thread, thenTisSync. - If
TisSync, then&Tcan be moved to another thread.
The definition makes sense once you see what "sharing" means in Rust. A value can be used by several threads at the same time only if each thread holds a &T. Handing a &T to another thread is a transfer of that reference, and transfers between threads are what Send governs. So the question "can this type be shared?" reduces to "can a reference to it be sent?".
This is not a convention you could change. The compiler treats Sync as the trait that holds whenever &T: Send holds. The standard library contains an implementation along the lines of unsafe impl<T: Sync + ?Sized> Send for &T {}. That line says a shared reference is Send when its target is Sync.
Checking the rule with the compiler
Empty generic functions let you ask the compiler about both sides of the equivalence.
use std::cell::Cell;
use std::sync::Mutex;
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
fn main() {
// Vec<i32> is Sync, so &Vec<i32> is Send.
assert_sync::<Vec<i32>>();
assert_send::<&Vec<i32>>();
// Mutex<i32> is Sync, so &Mutex<i32> is Send.
assert_sync::<Mutex<i32>>();
assert_send::<&Mutex<i32>>();
// Cell<i32> is Send, so it can move to another thread.
assert_send::<Cell<i32>>();
// Cell<i32> is not Sync, so &Cell<i32> is not Send.
// Each of these lines would fail to compile if uncommented:
// assert_sync::<Cell<i32>>();
// assert_send::<&Cell<i32>>();
}The two commented lines fail for the same underlying reason. Cell lets you mutate through a shared reference with no synchronization. If two threads held &Cell<i32> and both called set, they would race. Cell<i32> is therefore not Sync, and by the rule, &Cell<i32> is not Send.
Cell<i32> is still Send. Moving it wholesale to a single other thread leaves only one thread with access. This is the standard example of a type that is Send but not Sync.
The other reference: &mut T
The rule covers &T only. Mutable references follow a separate rule:
| Type | Is `Send` when |
|---|---|
| `&T` | `T: Sync` |
| `&mut T` | `T: Send` |
A &mut T is exclusive. Sending it gives the other thread the only access to the value, which is the same situation as sending the T itself. So &mut Cell<i32> is Send, while &Cell<i32> is not. Keep these two rows distinct, because the difference explains why a non-Sync value can still be handed to one worker thread by mutable borrow.
Why Mutex<T> is Sync when T is only Send
The rule produces an interesting result for Mutex<T>. The standard library declares roughly this:
unsafe impl<T: ?Sized + Send> Send for Mutex<T> {}
unsafe impl<T: ?Sized + Send> Sync for Mutex<T> {}Mutex<T> is Sync when T is only Send. T does not need to be Sync. The lock ensures that only one thread touches the inner value at a time, so the value is never accessed concurrently. In effect the mutex passes the value from thread to thread, one holder at a time. That is exactly what Send permits.
This means a Mutex can make a non-Sync type shareable:
use std::cell::Cell;
use std::sync::Mutex;
use std::thread;
fn main() {
let cell = Mutex::new(Cell::new(0));
thread::scope(|s| {
s.spawn(|| {
let guard = cell.lock().unwrap();
guard.set(guard.get() + 1);
});
s.spawn(|| {
let guard = cell.lock().unwrap();
guard.set(guard.get() + 1);
});
});
println!("{}", cell.lock().unwrap().get());
}This prints 2. Each spawned closure borrows &Mutex<Cell<i32>>. For that to be allowed, &Mutex<Cell<i32>> must be Send, which requires Mutex<Cell<i32>>: Sync, which requires Cell<i32>: Send. Every step holds, so the program compiles. You walked the rule from the closure's capture back to the inner type.
The difference between Mutex and RwLock is worth remembering:
| Type | Is `Sync` when |
|---|---|
| `Mutex<T>` | `T: Send` |
| `RwLock<T>` | `T: Send + Sync` |
RwLock allows several readers at once, and each reader gets a &T. Those readers run in parallel, so T itself must be Sync. A Mutex never hands out more than one reference at a time.
Using the rule to predict errors
When a compiler error mentions Send for a reference, translate it back to Sync on the target. Suppose a scoped thread borrows a Cell:
use std::cell::Cell;
use std::thread;
fn main() {
let counter = Cell::new(0);
thread::scope(|s| {
s.spawn(|| {
counter.set(counter.get() + 1);
});
});
}This does not compile. The closure captures &Cell<i32>, and thread::Scope::spawn requires the closure to be Send. The compiler reports that Cell<i32> cannot be shared between threads safely, and that the trait Sync is not implemented for it. It may also say that &Cell<i32> is required to be Send. Both lines describe one fact, stated once in terms of Sync and once in terms of Send.
Three common fixes follow from that diagnosis:
- Replace
Cell<i32>withAtomicI32, which isSync. - Replace it with
Mutex<i32>, which isSyncwheni32: Send. - Give each thread its own value and combine the results after joining.
How the rule applies to your own types
You rarely write Sync by hand. The compiler derives it, and the rule explains the outcome. A struct is Sync when every field is Sync. Put one Cell<u8> in a struct and the whole struct stops being Sync. Then &YourStruct is not Send, and no closure that captures a reference to it can cross a thread boundary.
When you do write unsafe impl Sync for X {}, you assert that &X is safe to send across threads. Check that every method taking &self is safe to run concurrently from several threads. If any &self method mutates state without synchronization, the impl is unsound.
Summary of the relationships
T: Syncis equivalent to&T: Send.&mut T: SendfollowsT: Send, notSync.- A type can be
Sendand notSync(Cell<T>,RefCell<T>). - A type can be
Syncand notSend(MutexGuard<T>whenT: Sync). Mutex<T>needs onlyT: Sendto beSync, because the lock serializes access.
Exercise
A struct Config has two fields: name: String and hits: Cell<u32>. A scoped thread captures &config in a closure. Does it compile? Name the trait the compiler complains about and give the reason. Then change one field's type so that it compiles and the counter still works.
Show answer
It does not compile. Cell<u32> is not Sync, so Config is not Sync. By the rule, &Config is then not Send, and the scoped closure that captures it cannot be sent to another thread. The error mentions Sync not being implemented for Cell<u32>. Changing hits to AtomicU32 (or Mutex<u32>) makes Config Sync, so &Config is Send and the program compiles. With AtomicU32 you update the counter using fetch_add(1, Ordering::Relaxed) instead of set.