Sub topic 13
Reading and fixing Send and Sync errors
This chapter assumes you know what Send and Sync promise, how thread::spawn bounds its closure, and the usual thread-safe types (Arc, Mutex, atomics).
Anatomy of the error
Start with a closure that moves an Rc into a thread:
use std::rc::Rc;
use std::thread;
fn main() {
let data = Rc::new(5);
let handle = thread::spawn(move || {
println!("{}", data);
});
handle.join().unwrap();
}The compiler reports (shortened):
error[E0277]: `Rc<i32>` cannot be sent between threads safely
| let handle = thread::spawn(move || {
| ------------- ^------
| | within this `{closure}`
= help: within `{closure}`, the trait `Send` is not implemented for `Rc<i32>`
= note: required because it's used within this closure
note: required by a bound in `spawn`Read it in three steps:
- The headline names the type and the missing trait:
Rc<i32>is notSend. - The "required because" lines trace a path from the bound down to the field that breaks it. With nested types, the last type in the chain is the culprit.
- The "required by a bound in" line names the function that demanded the trait. Here that is
spawn.
Sync errors arrive as Send errors
Sharing a non-Sync type behind an Arc fails in a less obvious way:
error[E0277]: `Cell<i32>` cannot be shared between threads safely
= help: the trait `Sync` is not implemented for `Cell<i32>`
= note: required for `Arc<Cell<i32>>` to implement `Send`Arc<T> is Send only when T is both Send and Sync. This follows from the rule that T is Sync exactly when &T is Send. The error shows up on Arc, but the fix belongs on the inner type.
Choosing the fix
| Culprit in the message | Typical fix |
|---|---|
| `Rc<T>` is not `Send` | Use `Arc<T>` |
| `Cell<T>` or `RefCell<T>` is not `Sync` | Use an atomic, or `Mutex<T>` / `RwLock<T>` |
| `MutexGuard` is not `Send` | Drop the guard before the thread boundary, or lock inside the thread |
| Raw pointer is not `Send` | Wrap it in a type with a justified `unsafe impl` |
| Closure may outlive borrowed value | Add `move`, or use `thread::scope` |
A fixed version
Replacing Rc<Cell<i32>> with Arc<AtomicI32> satisfies both bounds. This program prints 4.
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::Arc;
use std::thread;
fn main() {
let hits = Arc::new(AtomicI32::new(0));
let mut handles = Vec::new();
for _ in 0..4 {
let hits = Arc::clone(&hits);
handles.push(thread::spawn(move || {
hits.fetch_add(1, Ordering::SeqCst);
}));
}
for handle in handles {
handle.join().unwrap();
}
println!("{}", hits.load(Ordering::SeqCst));
}Debugging habits
- Use the
assert_send::<T>()helper from earlier in the tutorial to test a type in isolation. - Read the bottom of the error first. It names the type that fails, and the top often repeats the whole closure.
- If a closure captures several values, remove them one at a time to find which one fails.
Exercise
A program wraps a RefCell<Vec<i32>> in an Arc and passes clones to spawned threads. The compiler says RefCell<Vec<i32>> cannot be shared between threads safely. Why does the error mention Arc as well, and what is the smallest change that fixes it?
Show answer
Arc<T> is Send only if T is Send + Sync. RefCell is not Sync, so Arc<RefCell<Vec<i32>>> is not Send, and spawn rejects the closure. Replace RefCell with Mutex, giving Arc<Mutex<Vec<i32>>>, and call .lock().unwrap() where you used .borrow_mut().