Sub topic 4
Send and Sync: the rules behind safe threading
This chapter assumes you know ownership, borrowing, trait bounds, and thread::spawn with move closures from earlier chapters. It explains the two marker traits the compiler checks whenever data crosses a thread boundary.
Two questions the compiler asks
Rust doesn't track threads in the type system directly. It asks two questions about a type T.
T: Sendmeans ownership of aTcan move to another thread.T: Syncmeans a&Tcan be shared with other threads. Formally,TisSyncexactly when&TisSend.
Both are marker traits. They have no methods. They are also auto traits. The compiler implements them for a type when all of its fields implement them. A struct made of Send fields is Send without any code from you.
Where the checks happen
The signature of thread::spawn carries the rule:
- The closure must be
Sendand'static. - Its return type must be
Sendand'static.
Every value the closure captures by move becomes part of the closure. If one captured value is not Send, the whole closure is not Send, and the call fails to compile. That is how a data race becomes a compile-time error instead of a runtime bug.
Types that opt out
A few standard types are deliberately not thread-safe, because the cheaper non-atomic version is useful on a single thread.
| Type | Send | Sync | Reason |
|---|---|---|---|
| `i32`, `String`, `Vec<T>` (with `T: Send`) | yes | yes | plain owned data |
| `Rc<T>` | no | no | its reference count is not atomic |
| `Cell<T>`, `RefCell<T>` | yes | no | interior mutation without locking |
| `Arc<T>` | if `T: Send + Sync` | if `T: Send + Sync` | atomic count, but `T` is shared |
| `Mutex<T>` | if `T: Send` | if `T: Send` | the lock serializes access |
| `*const T`, `*mut T` | no | no | the compiler can't reason about raw pointers |
Two entries need explanation.
Rc<T> fails because two threads could update its counter at the same time and corrupt it. If you pass an Rc into thread::spawn, the compiler reports that `Rc<i32> cannot be sent between threads safely`. Switch to Arc`.
Cell and RefCell are Send but not Sync. Moving one to a single other thread is safe, because only one thread owns it. Sharing a &RefCell between threads is not, because both threads could mutate it with no synchronization. Mutex<T> is the thread-safe version of that idea. It is Sync even when T is only Send, because only one thread at a time gets access.
Checking a type yourself
You can ask the compiler about any type by writing a function with a trait bound and calling it. If the call compiles, the type has the trait.
use std::cell::Cell;
use std::sync::{Arc, Mutex};
fn is_send<T: Send>() {}
fn is_sync<T: Sync>() {}
fn main() {
is_send::<Arc<Mutex<i32>>>();
is_sync::<Arc<Mutex<i32>>>();
is_send::<Cell<i32>>();
// is_sync::<Cell<i32>>(); // error: `Cell<i32>` cannot be shared between threads safely
// is_send::<std::rc::Rc<i32>>(); // error: `Rc<i32>` cannot be sent between threads safely
println!("all checks passed");
}Uncomment either error line to see the compiler's message.
Common errors
- Reaching for
Rcin threaded code. UseArc. The cost of atomic counting is small. - Putting a
RefCellinside anArc.Arc<RefCell<T>>is notSend, becauseRefCell<T>is notSync. UseArc<Mutex<T>>. - Holding a
MutexGuardacross a thread boundary. The guard is notSend. Lock inside the thread that uses the data. - Implementing
unsafe impl Sendto silence an error. Doing this promises the compiler the type is safe. A wrong promise brings back data races. Do it only when you can justify it.
Exercise
Why is Arc<RefCell<i32>> rejected by thread::spawn, and which type would you use instead?
Show answer
RefCell<i32> is not Sync, so Arc<RefCell<i32>> is not Send. Two threads holding the same Arc could mutate the cell at the same time. Use Arc<Mutex<i32>>, because Mutex<i32> is Sync and serializes access.