Sub topic 7
Types that are not Send
This chapter assumes you know thread::spawn, move closures, and trait bounds. It also assumes you know that Send is a marker trait for values whose ownership can move to another thread. Here you learn which standard types opt out of Send and why.
Why some types opt out
The compiler implements Send automatically for a type when all of its fields are Send. A type becomes non-Send in one of two ways. It contains a field that is not Send, or its author explicitly opted out because moving it across threads would be unsound.
Rc: a non-atomic reference count
Rc<T> updates its reference count with plain, non-atomic operations. If two threads each held a clone, they could update the count at the same time and corrupt it. The compiler therefore rejects this program:
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 error says Rc<i32> cannot be sent between threads safely. The fix is Arc<T>, which uses atomic counting and is Send when T is Send and Sync.
Raw pointers
*const T and *mut T are not Send. The compiler cannot tell who owns the data behind a raw pointer or whether other code aliases it. Any struct that holds a raw pointer inherits this restriction, even if the struct is safe in practice.
MutexGuard
MutexGuard<'_, T> is not Send. Some operating-system lock implementations require the thread that locked a mutex to be the one that unlocks it. If a guard could move to another thread, dropping it there would break that rule. The guard also borrows the mutex, so it is meant to stay in the scope where you locked it.
Checking a type directly
A function with a Send bound but an empty body lets you ask the compiler whether a type is Send:
use std::sync::Arc;
fn assert_send<T: Send>() {}
fn main() {
assert_send::<String>();
assert_send::<Arc<i32>>();
assert_send::<Box<Vec<u8>>>();
// 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>>();
}Common mistakes
- Cloning an
Rcinto a spawned closure. Switch toArc. - Holding a
MutexGuardin a value that moves to another thread. Drop the guard first, or copy the data you need out of it. - Wrapping a raw pointer in a struct and then passing the struct to
thread::spawn. The struct is notSenduntil you write anunsafe impl, which is covered in a later chapter.
| Type | Send? | Reason |
|---|---|---|
| `String`, `Vec<i32>` | Yes | All fields are `Send` |
| `Arc<i32>` | Yes | Atomic reference count |
| `Rc<i32>` | No | Non-atomic reference count |
| `*mut i32` | No | Compiler cannot reason about aliasing |
| `MutexGuard<'_, i32>` | No | Lock must be released on the locking thread |
Exercise
A struct has fields name: String and cache: Rc<Vec<u8>>. Can you pass it into thread::spawn? What is the smallest change that makes it work?
Show answer
No. Rc<Vec<u8>> is not Send, so the struct is not Send either, because the compiler derives Send only when every field is Send. Changing the field to Arc<Vec<u8>> makes the struct Send, since Vec<u8> is both Send and Sync.