Sub topic 4
Send and Sync: why Rc is rejected and Arc is accepted
This chapter assumes you know Rust ownership and borrowing, closures with move, and the basics of thread::spawn and JoinHandle. It also assumes you are comfortable with Result and unwrap. By the end you should be able to read a "cannot be sent between threads safely" error and say which type caused it and why.
The compiler checks threads through traits
Rust has no special thread-safety pass. thread::spawn is an ordinary function, and its signature carries the rules:
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,The closure F must be Send, and so must its return value T. A closure is Send only if every value it captures is Send. Moving an Rc into the closure makes the closure not Send, and the call fails to type-check.
What Send and Sync mean
Both are marker traits. They have no methods. They only record a fact about a type.
T: Sendmeans ownership of aTcan be moved to another thread.T: Syncmeans&Tcan be shared between threads. Formally,TisSyncexactly when&TisSend.
These two definitions are linked. If several threads each hold a &T, then &T has been sent to those threads. So Sync is Send applied to shared references.
Both traits are auto traits. The compiler implements them for a struct or enum when all of its fields implement them. You rarely write impl Send yourself. Types opt out, usually because they contain a raw pointer or because a standard library type explicitly declares itself !Send or !Sync.
Why Rc is rejected
Rc<T> keeps a reference count that it updates with plain, non-atomic reads and writes. If two threads cloned or dropped clones of the same Rc at once, both could read the same count and write back the same new value. The count would drift. It could reach zero while a clone still exists, and the value would be freed too early. That is a use-after-free.
The standard library prevents this by marking Rc<T> as neither Send nor Sync:
use std::rc::Rc;
use std::sync::Mutex;
use std::thread;
fn main() {
let data = Rc::new(Mutex::new(0));
let data2 = Rc::clone(&data);
// Does not compile: `Rc<Mutex<i32>>` cannot be sent between threads safely.
let handle = thread::spawn(move || {
*data2.lock().unwrap() += 1;
});
handle.join().unwrap();
}The error reads roughly:
error[E0277]: `Rc<Mutex<i32>>` cannot be sent between threads safely
= help: within `{closure}`, the trait `Send` is not implemented for `Rc<Mutex<i32>>`
= note: required because it's used within this closure
note: required by a bound in `spawn`Read it from the bottom. The bound Send comes from spawn. The closure is not Send because it captured an Rc<Mutex<i32>>. The Mutex is not the problem. It is the Rc wrapped around it.
Why Arc is accepted
Arc<T> has the same job as Rc<T>, but it updates its count with atomic operations. Concurrent clones and drops cannot corrupt the count. The price is that each update is slower than a plain increment.
The standard library declares:
Arc<T>isSendifT: Send + Sync.Arc<T>isSyncifT: Send + Sync.
The condition on T matters. An Arc hands out shared access to the same T from many threads, and the last thread to drop its clone also drops the T. That means T must be safe to share (Sync) and safe to destroy on a different thread (Send). The atomic count does not protect T itself.
The fix for the broken example is a one-word change from Rc to Arc:
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let data = Arc::new(Mutex::new(0));
let data2 = Arc::clone(&data);
let handle = thread::spawn(move || {
*data2.lock().unwrap() += 1;
});
handle.join().unwrap();
println!("{}", *data.lock().unwrap());
}This prints 1. Mutex<i32> is Send + Sync, so Arc<Mutex<i32>> is Send, so the closure is Send.
Where Mutex fits
Mutex<T> is the reason the pattern works. Its rules are:
Mutex<T>isSendifT: Send.Mutex<T>isSyncifT: Send.
The second rule is unusual. T does not need to be Sync, because the lock allows only one thread at a time to touch it. A Mutex turns a Send-only type into something that can be shared. This is why a Mutex<RefCell<i32>> can be shared between threads even though RefCell<i32> cannot.
The requirement is still real. Arc<Mutex<Rc<i32>>> is rejected, because Rc<i32> is not Send. A lock around the Rc does not help: the Rc could be cloned inside the lock, and a clone could escape to another thread and outlive the lock.
Checking traits yourself
You can ask the compiler about any type with two empty helper functions. A call compiles only if the bound holds:
use std::cell::RefCell;
use std::sync::{Arc, Mutex};
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
fn main() {
assert_send::<i32>();
assert_sync::<Mutex<i32>>();
assert_send::<Arc<Mutex<Vec<i32>>>>();
assert_send::<RefCell<i32>>();
// assert_sync::<RefCell<i32>>(); // error: `RefCell<i32>` cannot be shared between threads safely
// assert_send::<std::rc::Rc<i32>>(); // error: `Rc<i32>` cannot be sent between threads safely
println!("all bounds hold");
}Uncomment a line to see its error. This trick is useful when you design a type and want to confirm it stays thread-safe as you add fields.
Reference table
| Type | Send | Sync | Reason |
|---|---|---|---|
| `i32`, `String`, `Vec<T>` (T: Send/Sync) | yes | yes | Plain owned data. |
| `Rc<T>` | no | no | Non-atomic reference count. |
| `Arc<T>` | if `T: Send + Sync` | if `T: Send + Sync` | Atomic reference count. |
| `Cell<T>`, `RefCell<T>` | if `T: Send` | no | Mutation through `&self` without synchronization. |
| `Mutex<T>` | if `T: Send` | if `T: Send` | The lock serializes access. |
| `RwLock<T>` | if `T: Send` | if `T: Send + Sync` | Readers share `&T` at the same time. |
| `MutexGuard<'_, T>` | no | if `T: Sync` | A guard must be released by the thread that locked it on some platforms. |
| `*const T`, `*mut T` | no | no | The compiler assumes nothing about raw pointers. |
Cell and RefCell show that Send and Sync are independent. You can move a RefCell to another thread, because only one thread owns it afterward. You cannot share &RefCell between threads, because two threads could call borrow_mut at once and its borrow flag is not atomic.
Gotchas
- Errors point at the closure, not the type. The message names the closure, then the captured variable. Look at what you moved in.
- Holding a guard across a thread boundary fails.
MutexGuardis notSend, so you cannot return one from a spawned thread or move one into another thread. Copy or clone the data out and drop the guard first. - Scoped threads relax
'static, notSend. Insidethread::scopeyou can borrow locals, but a&TisSendonly ifT: Sync. Borrowing aRefCellfrom two scoped threads is rejected for that reason. - A struct inherits the weakest field. One
Rcor raw pointer field makes the whole struct!Sendand!Sync.
How the checks fit together
Summary of the rules
spawnrequiresSendon the closure and its result.- A closure is
Sendif all its captures areSend. Rcis!Sendand!Syncbecause its count is not atomic.Arc<T>isSendandSynconly whenTis both.Mutex<T>isSyncwhenT: Send, which is what letsArc<Mutex<T>>carry non-Syncdata across threads.
Exercise
The following code does not compile. Which trait bound fails, which captured value causes it, and what is the smallest change that makes it compile and print 3? use std::cell::RefCell; use std::sync::Arc; use std::thread; fn main() { let value = Arc::new(RefCell::new(0)); let v2 = Arc::clone(&value); thread::spawn(move || { *v2.borrow_mut() += 3; }) .join() .unwrap(); println!("{}", value.borrow()); }
Show answer
Arc<RefCell<i32>> is Send only if RefCell<i32> is Send + Sync, but RefCell is not Sync. So the Send bound on the closure fails because of the captured v2. The Arc cannot rescue it, since the atomic count does not protect the inner value. Replace RefCell with Mutex: use Arc::new(Mutex::new(0)), *v2.lock().unwrap() += 3;, and print *value.lock().unwrap(). Mutex<i32> is Sync, so the code compiles and prints 3.