Sub topic 13
Reading and fixing Send and Sync errors
This chapter assumes you know ownership and borrowing, trait bounds, move closures, and basic use of thread::spawn. You should also know what Send and Sync promise and which standard types opt out. Here the focus is the compiler's output: how to find the real cause in a long message and pick the right fix.
Anatomy of a Send or Sync error
Almost every error in this family is E0277, "the trait bound is not satisfied". The compiler checks a bound such as F: Send + 'static on thread::spawn. It fails, then explains why. The explanation has three layers, and each answers a different question:
- The headline names the type and the property that is missing, for example "
Rc<i32>cannot be sent between threads safely". - The
helpline names the trait and the type that lacks it. This is the root cause. - The
note: required because ...lines are a chain from the root cause up to the bound you wrote. They show the path through your types, closures, and wrappers.
Read the messages bottom-up for the path and top-down for the cause. The last note: required by a bound in ... tells you which function demanded the trait. The help line tells you which type to change.
Case 1: a non-Send value in a closure
This is the classic case. It does not compile.
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 relevant part of the output looks like this (exact spans vary by compiler version):
error[E0277]: `Rc<i32>` cannot be sent between threads safely
|
| let handle = thread::spawn(move || {
| ------------- ^------
| | |
| | `Rc<i32>` cannot be sent between threads safely
| required by a bound introduced by this call
|
= 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`The headline and the help line both point at Rc<i32>. The note says the Rc was captured by the closure, and the closure is what spawn requires to be Send. A closure is Send only if every captured value is Send. The fix is to use the atomic version of the pointer: Arc.
When the offending type is buried in one of your own structs, the chain gets longer. The compiler adds a line such as "required because it appears within the type Job". Follow it down to the field with the non-Send type, and fix that field.
use std::sync::Arc;
use std::thread;
struct Job {
name: String,
table: Arc<Vec<i32>>, // was Rc<Vec<i32>>
}
fn main() {
let job = Job {
name: String::from("sum"),
table: Arc::new(vec![1, 2, 3]),
};
let handle = thread::spawn(move || {
let total: i32 = job.table.iter().sum();
println!("{} = {}", job.name, total);
});
handle.join().unwrap();
}Job is Send here because String and Arc<Vec<i32>> are both Send. The compiler derives this automatically, with no impl needed.
Case 2: a type that is Send but not Sync
Arc<T> can be sent to another thread only if T is both Send and Sync. Two threads holding clones of the Arc can each call &T methods at once, so T must tolerate shared references. Cell<i32> is Send but not Sync, so this fails:
use std::cell::Cell;
use std::sync::Arc;
use std::thread;
fn main() {
let counter = Arc::new(Cell::new(0));
let c = Arc::clone(&counter);
let handle = thread::spawn(move || {
c.set(c.get() + 1);
});
handle.join().unwrap();
}The error reads "Cell<i32> cannot be shared between threads safely". The help line says Sync is not implemented for Cell<i32>. A note then says this is required for Arc<Cell<i32>> to implement Send. The message mentions Sync while the failing bound is Send on the Arc. That is the Sync-through-Send relationship at work, so do not look for a missing Send on Cell itself.
Pick the replacement by how the data is used:
| Non-Sync type | Replacement | Use when |
|---|---|---|
| `Cell<i32>` and other small `Copy` values | `AtomicI32` and the other atomics | A single integer or flag with simple updates |
| `Cell<T>` or `RefCell<T>` for a larger `T` | `Mutex<T>` | Any access pattern, writes are common |
| `RefCell<T>` read often, written rarely | `RwLock<T>` | Many concurrent readers |
An atomic version of the previous program:
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::Arc;
use std::thread;
fn main() {
let counter = Arc::new(AtomicI32::new(0));
let mut handles = Vec::new();
for _ in 0..4 {
let c = Arc::clone(&counter);
handles.push(thread::spawn(move || {
c.fetch_add(1, Ordering::Relaxed);
}));
}
for handle in handles {
handle.join().unwrap();
}
println!("{}", counter.load(Ordering::SeqCst));
}It prints 4. AtomicI32 is Sync, so Arc<AtomicI32> is Send.
Case 3: a missing bound in generic code
In generic functions the error lands on a type parameter, not on a concrete type. The compiler cannot know that an arbitrary T is safe to move across threads.
use std::thread;
fn run_in_thread<T: Send + 'static>(value: T) {
thread::spawn(move || drop(value)).join().unwrap();
}
fn main() {
run_in_thread(String::from("hi"));
}Without Send, the message is "T cannot be sent between threads safely", and it includes a suggestion: "consider restricting type parameter T". That suggestion is usually correct. Without 'static, you get a separate error saying the parameter type may not live long enough. spawn demands both, because the new thread can outlive the caller.
Adding bounds moves the requirement to callers. Passing an Rc<i32> to run_in_thread now fails at the call site, which is where the choice belongs.
Case 4: the 'static half of the spawn bound
Not every spawn error is about Send. Borrowing a local variable in a plain thread::spawn closure produces E0373, "closure may outlive the current function".
use std::thread;
fn main() {
let v = vec![1, 2, 3];
let handle = thread::spawn(|| {
println!("{:?}", v);
});
handle.join().unwrap();
}The compiler suggests move. That works, but gives the thread ownership of v, so the main thread can no longer use it. If you need to keep using the data, use a scoped thread. The scope guarantees every spawned thread finishes before it returns, so borrowed data is allowed.
use std::thread;
fn main() {
let v = vec![1, 2, 3];
thread::scope(|s| {
s.spawn(|| println!("first: {:?}", v));
s.spawn(|| println!("len: {}", v.len()));
});
println!("still usable: {:?}", v);
}Both threads share &Vec<i32>, which is allowed because Vec<i32> is Sync. Scoped threads relax the 'static bound but keep the Send requirement. A Cell in v would still be rejected.
Case 5: a guard that crosses a thread boundary
MutexGuard is not Send, because some platforms require the thread that locked a mutex to unlock it. Errors appear when you try to move a guard into a spawned closure, or hold one across an .await in a future that must be Send. The fix is to shorten the guard's lifetime. Copy or clone the data out, then drop the guard before the boundary:
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let shared = Arc::new(Mutex::new(vec![1, 2, 3]));
let snapshot = shared.lock().unwrap().clone(); // guard dropped at end of statement
let handle = thread::spawn(move || {
println!("{:?}", snapshot);
});
handle.join().unwrap();
}Clone the data and drop the guard in the same statement, as above. Binding the guard to a variable keeps the lock held until the end of the scope.
A checklist for any error in this family
- Read the
helpline. It names the type missingSendorSync. - Decide which trait the failing bound really needs. A missing
Syncoften surfaces as aSendrequirement onArc<T>,&T, or a closure that captures a reference. - Follow the
required becausenotes to the field, capture, or generic parameter that introduced the type. - Replace the type with its thread-safe counterpart, or restructure so the value never crosses the boundary.
- Add bounds to a generic only when callers can reasonably meet them.
Exercise
This program fails to compile with "RefCell<Vec<i32>> cannot be shared between threads safely". Which trait is missing on RefCell, which bound on Arc produced the error, and what is the smallest change that fixes it?
use std::cell::RefCell;
use std::sync::Arc;
use std::thread;
fn main() {
let log = Arc::new(RefCell::new(Vec::new()));
let l = Arc::clone(&log);
thread::spawn(move || l.borrow_mut().push(1)).join().unwrap();
}
Show answer
RefCell<Vec<i32>> lacks Sync. Arc<T> implements Send only when T: Send + Sync, and spawn requires the closure, which captures the Arc, to be Send. The smallest fix is to replace RefCell with Mutex, and change borrow_mut() to lock().unwrap(). Mutex<Vec<i32>> is Sync because Vec<i32> is Send.