Sub topic 4
Send and Sync: Why Rc Is Rejected and Arc Is Accepted
This chapter assumes you know ownership and borrowing, move closures, and thread::spawn with JoinHandle. You should also be able to read a compiler error. The chapter explains the compile-time check that stops you from sharing data across threads unsafely.
Two marker traits
Send and Sync are marker traits. They have no methods. The compiler implements them automatically for a type when all of its fields have them.
T: Sendmeans a value of typeTcan be moved to another thread.T: Syncmeans a shared reference&Tcan be used from several threads at once. Equivalently,TisSyncwhen&TisSend.
thread::spawn requires its closure to be Send + 'static. A closure is Send only if every value it captures is Send. This is where the check happens.
Why Rc is rejected
Rc<T> keeps its reference count in a plain integer. If two threads cloned or dropped an Rc at the same moment, they could corrupt the count. The data could then be freed too early or never freed. So Rc<T> is 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 names the missing trait: `the trait Send is not implemented for Rc<Mutex<i32>> . The compiler traces it to the captured variable data2`.
Why Arc is accepted
Arc<T> has the same job as Rc<T>, but it updates its count with atomic operations. These are safe when several threads touch the count at once. Replacing Rc with Arc makes the program compile.
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.
How the check composes
Arc<T> is Send and Sync only when T is both Send and Sync. The atomic count is safe, but the data inside must be safe to share too.
| Type | Send | Sync |
|---|---|---|
| `Rc<T>` | no | no |
| `Arc<T>` | if `T: Send + Sync` | if `T: Send + Sync` |
| `Mutex<T>` | if `T: Send` | if `T: Send` |
| `RefCell<T>` | if `T: Send` | no |
| `MutexGuard<T>` | no | if `T: Sync` |
Mutex<T> is Sync even when T is not, as long as T is Send. The lock allows only one thread at a time to reach the value. This is why Arc<Mutex<RefCell<i32>>> compiles, but Arc<RefCell<i32>> does not.
Common mistakes
- Treating
Arcas the thing that makes data thread-safe.Arconly makes the reference count safe. You still needMutex,RwLockor an atomic type to mutate the value. - Holding a
MutexGuardacross a thread boundary. The guard is notSend, because some platforms require the thread that locked a mutex to be the one that unlocks it. - Reaching for
unsafe impl Sendto silence an error. That promises the compiler you checked the safety yourself. Fix the type instead.
Exercise
Why does Arc<RefCell<i32>> fail to compile when moved into thread::spawn, and what is the usual fix?
Show answer
Arc<T> is Send only if T is Send + Sync. RefCell<i32> is not Sync, because its borrow flag is not atomic, so the closure is not Send. Replace RefCell with Mutex, giving Arc<Mutex<i32>>. For a plain integer, an atomic type such as AtomicI32 also works.