Sub topic 7
Types that are not Send
This chapter assumes you know ownership and move closures, can read trait bounds such as T: Send + 'static, and have used thread::spawn and JoinHandle. Earlier chapters covered what Send promises and how the compiler derives it automatically. Here you learn which types opt out, why each one does, and how to fix the errors they cause.
What "not Send" means
T: Send means ownership of a T can move to another thread. A type is not Send when moving it, or dropping it, on a different thread than the one that created it could break a safety rule.
Three reasons account for nearly every case:
- The type uses shared, non-atomic bookkeeping, as
Rcdoes. - The type holds a raw pointer, and the compiler cannot know who owns the target.
- The type depends on thread identity, as
MutexGuarddoes on some platforms.
Rc: non-atomic reference counting
Rc<T> keeps a plain integer counter of its clones. Two clones can live on different threads and both be dropped at once. Both threads would then do an unsynchronized read-modify-write on the same counter. That is a data race. The count could end too low, which frees the value while a clone still points at it. It could also end too high, which leaks the value.
Moving even one clone to another thread is not allowed, because the other clones stay behind and still share the counter. So Rc<T> is not Send for any T.
use std::rc::Rc;
use std::thread;
fn main() {
let data = Rc::new(5);
let handle = thread::spawn(move || {
println!("{}", data);
});
handle.join().unwrap();
}This program does not compile. The error looks like this:
error[E0277]: `Rc<i32>` cannot be sent between threads safely
= help: the trait `Send` is not implemented for `Rc<i32>`
note: required by a bound in `spawn`The fix is Arc<T>, which uses atomic operations for its counter. Arc<T> costs a little more per clone, so use Rc in single-threaded code and Arc when the value crosses threads.
Raw pointers
*const T and *mut T are neither Send nor Sync. A raw pointer carries no ownership or lifetime information. The compiler cannot tell whether the target is unique, shared, or thread-bound, so it assumes the worst. NonNull<T> behaves the same way.
This matters because a raw pointer inside a struct makes the whole struct non-Send. Types such as Vec<T> and Box<T> contain raw pointers internally. The standard library marks them Send with an unsafe impl, where T must also be Send. When you wrap a raw pointer yourself, you must make that decision yourself. A later chapter covers it.
MutexGuard
MutexGuard<'_, T> is the value you get from lock(). It is not Send. On some platforms, such as those using POSIX mutexes, unlocking a mutex from a different thread than the one that locked it is undefined behavior. The compiler prevents this by forbidding the guard from crossing threads.
use std::sync::Mutex;
use std::thread;
fn main() {
let m = Mutex::new(0);
let guard = m.lock().unwrap();
thread::scope(|s| {
s.spawn(move || {
// error: `MutexGuard<'_, i32>` cannot be sent between threads safely
drop(guard);
});
});
}The fix is to take the lock on the thread that needs it:
use std::sync::Mutex;
use std::thread;
fn main() {
let m = Mutex::new(0);
thread::scope(|s| {
s.spawn(|| {
*m.lock().unwrap() += 1;
});
});
println!("{}", m.lock().unwrap());
}This version compiles and prints 1. Sharing &Mutex<i32> across threads works because Mutex<i32> is Sync. Only the guard is tied to its thread.
References and conditional Send
Some types are Send only when their parameters are. This table lists common cases.
| Type | Send? | Reason |
|---|---|---|
| `i32`, `String`, `Vec<T>` where `T: Send` | Yes | Plain owned data |
| `Cell<T>`, `RefCell<T>` where `T: Send` | Yes | Moving the whole cell leaves no other owner behind |
| `Mutex<T>` where `T: Send` | Yes | Ownership transfer is safe if `T` can move |
| `Receiver<T>` where `T: Send` | Yes | Receiving end of a channel can move to one thread |
| `&T` | Only if `T: Sync` | A shared reference is `Send` exactly when `T` is `Sync` |
| `&mut T` | Only if `T: Send` | Exclusive access is like temporary ownership |
| `Arc<T>` | Only if `T: Send + Sync` | Any clone may drop or read `T` on any thread |
| `Rc<T>`, `Weak<T>` from `std::rc` | Never | Non-atomic counts |
| `*const T`, `*mut T`, `NonNull<T>` | Never | No ownership information |
| `MutexGuard<'_, T>` | Never | Unlock must happen on the locking thread |
| `Ref<'_, T>`, `RefMut<'_, T>` | Never | They borrow a `RefCell`, which is not `Sync` |
The Arc<T> row surprises many people. Arc<RefCell<i32>> is not Send, even though Arc is atomic. Cloning an Arc lets two threads hold &RefCell<i32> at once, and RefCell is not Sync. The Send + Sync requirement on T stops this.
Checking a type directly
You can ask the compiler about any type with an empty function that has a Send bound:
use std::cell::{Cell, RefCell};
use std::sync::mpsc::Receiver;
use std::sync::{Arc, Mutex};
fn assert_send<T: Send>() {}
fn main() {
assert_send::<Cell<i32>>();
assert_send::<RefCell<String>>();
assert_send::<Receiver<i32>>();
assert_send::<Arc<Mutex<i32>>>();
assert_send::<Box<dyn Fn() + Send>>();
// Each of these lines would fail to compile if uncommented:
// assert_send::<std::rc::Rc<i32>>();
// assert_send::<*const i32>();
// assert_send::<std::sync::MutexGuard<'static, i32>>();
// assert_send::<Arc<Cell<i32>>>();
// assert_send::<Box<dyn Fn()>>();
}The last commented line shows trait objects. Box<dyn Fn()> is not Send, because the trait object hides the concrete type and the compiler assumes nothing. You must write Box<dyn Fn() + Send> to promise it.
Non-Send spreads through your types
Send is an auto trait. A struct is Send only if every field is Send. One Rc field makes the whole struct non-Send, and so does anything that contains that struct.
use std::rc::Rc;
use std::thread;
struct Job {
id: u32,
log: Rc<String>,
}
fn main() {
let job = Job { id: 1, log: Rc::new(String::from("start")) };
thread::spawn(move || {
println!("{} {}", job.id, job.log);
});
}This does not compile. The error names the offending field in a note, such as `within Job, the trait Send is not implemented for Rc<String> . Read the note below the headline, because it names the field. Then replace Rc with Arc, or build the Rc` inside the thread so it never crosses.
Common mistakes
- Switching to
Arcand keepingRefCellinside. TheArcstops complaining about the counter, butArc<RefCell<T>>is still notSend. UseArc<Mutex<T>>orArc<RwLock<T>>. - Holding a non-
Sendvalue across.await. An async block that keeps anRcor aMutexGuardalive over an await point becomes a non-Sendfuture. Multi-threaded executors then reject it. A later chapter covers this. - Casting a pointer to
usizeto dodge the check. This compiles, but it throws away the safety the compiler was enforcing. If the pointer really is safe to send, say so with a documented wrapper.
Summary of the working model
A value is non-Send when a move to another thread, or a drop there, could race with something left behind or violate a thread-bound rule. Rc, raw pointers, and MutexGuard are the base cases. Composite types inherit the property automatically. Fix errors by choosing a thread-safe replacement (Arc, Mutex), by changing where the value is created or locked, or by shrinking what the closure captures.
Exercise
This code fails with "Rc<Vec<i32>> cannot be sent between threads safely". A teammate changes Rc to Arc and the code still fails, now with an error about RefCell<Vec<i32>> and Sync. What is the correct fix, and why did the first change not suffice?
use std::cell::RefCell;
use std::rc::Rc;
use std::thread;
fn main() {
let shared = Rc::new(RefCell::new(vec![1, 2, 3]));
let s2 = Rc::clone(&shared);
thread::spawn(move || s2.borrow_mut().push(4)).join().unwrap();
println!("{:?}", shared.borrow());
}
Show answer
Use Arc<Mutex<Vec<i32>>>, cloning the Arc for the thread and calling lock().unwrap() instead of borrowmut() and borrow(). Arc<T> is Send only when T is both Send and Sync. RefCell<Vec<i32>> is Send but not Sync, because its borrow flag is a plain non-atomic value that two threads could update at once. Replacing Rc with Arc fixes the reference count but leaves the RefCell, so Arc<RefCell<>> is still not Send. Mutex<Vec<i32>> is Sync when Vec<i32> is Send, so Arc<Mutex<Vec<i32>>> satisfies the bound.
Exercise
A function takes a MutexGuard<'_, i32> as a parameter and spawns a thread that uses it. Explain why this cannot compile and give two ways to restructure it.
Show answer
MutexGuard is not Send, because a mutex may need to be unlocked on the same thread that locked it, so the guard cannot move into the spawned thread's closure. Restructure option one: pass &Mutex<i32> (using thread::scope, or an Arc<Mutex<i32>> with thread::spawn) and call lock() inside the new thread. Option two: do the work that needs the guard on the current thread, copy out the result (for example let value = *guard;), drop the guard, and send only the plain i32 to the new thread.