Sub topic 3
Send: Moving Values to Another Thread
This chapter assumes you know ownership and borrowing, trait bounds, closures with move, and the basics of thread::spawn and JoinHandle. It covers Send, the trait that decides whether a value can move to another thread. Sync, auto traits and manual unsafe impl have their own chapters, so they appear here only where needed.
What Send promises
Send is a marker trait, meaning it has no methods. A type T is Send if ownership of a T value can be transferred to another thread, and that thread can then use it and drop it, without causing a data race or other undefined behavior.
The question is not whether the type is useful on several threads at once. The question is whether the value can leave the thread that created it. A value that is Send is safe to use on the new thread because the old thread no longer touches it. A type loses Send when it contains something tied to its original thread, or something unsynchronized that other copies may still reach.
Where the compiler checks it
The check happens in the signature of thread::spawn. In simplified form it is:
F: FnOnce() -> T + Send + 'staticT: Send + 'static
The closure F is Send only if everything it captures is Send. The return type T must be Send too, because the result travels back to the thread that calls join. You never write Send on your own types in normal code. The compiler checks the bound at each spawn call.
use std::thread;
fn main() {
let name = String::from("worker-1");
let handle = thread::spawn(move || {
format!("hello from {name}")
});
println!("{}", handle.join().unwrap());
}This prints hello from worker-1. String is Send, so the move closure that captured it is Send. The returned String is Send, so it can come back through join.
Send also applies to channels
Send shows up wherever values cross threads, not only in spawn. A Sender<T> can be moved to another thread only if T is Send, because every value sent through it ends up on a different thread.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel::<Vec<u32>>();
let producer = thread::spawn(move || {
for i in 1..=3 {
tx.send(vec![i; i as usize]).unwrap();
}
});
for v in rx {
println!("{:?}", v);
}
producer.join().unwrap();
}The output is [1], then [2, 2], then [3, 3, 3]. Each Vec<u32> is allocated on the producer thread and then owned by the main thread. The loop over rx ends when tx is dropped, which happens when the producer closure finishes.
A type that is not Send
The standard example is Rc<T>. Its reference count is a plain integer, not an atomic one. If two threads each held an Rc pointing to the same allocation and both cloned or dropped it, the count could be corrupted. So Rc<T> is not Send.
The rule applies to return values as well as captures. This does not compile:
use std::rc::Rc;
use std::thread;
fn main() {
let handle = thread::spawn(|| Rc::new(5));
let value = handle.join().unwrap();
println!("{}", value);
}The compiler reports that Rc<i32> cannot be sent between threads safely, and that the trait Send is not implemented for it. Nothing is shared here, since the Rc is created on the new thread and has one owner. The compiler still rejects it, because Send is a property of the type, not of one particular value. The compiler does not track whether other clones exist, so it rejects every Rc.
The fix depends on intent. If you need shared ownership across threads, use Arc<T>, which has an atomic count. If you only need to return a number, return the i32 and build the Rc on the receiving side.
Common types and their Send status
| Type | Send? | Reason |
|---|---|---|
| `i32`, `String`, `Vec<T>` | Yes, when `T` is Send | Plain owned data. |
| `Rc<T>` | No | Non-atomic reference count. |
| `*const T`, `*mut T` | No | The compiler makes no assumptions about raw pointers. |
| `MutexGuard<'_, T>` | No | The lock must be released by the thread that took it. |
| `Cell<T>`, `RefCell<T>` | Yes, when `T` is Send | Moving the whole cell moves its only owner. |
| `Arc<T>` | Only when `T` is Send and Sync | Any clone can hand out `&T` on another thread. |
| `&T` | Only when `T` is Sync | Sending a shared reference lets another thread read the value. |
| `&mut T` | Only when `T` is Send | Exclusive access moves with the reference. |
| `Box<dyn Trait>` | No, unless written `Box<dyn Trait + Send>` | The concrete type is hidden. |
Two rows deserve attention. Cell<T> is Send because a move transfers the sole owner, so no two threads can touch it. MutexGuard is not Send because it is tied to the thread that holds the lock. Some platforms require unlocking on the same thread that locked.
Trait objects hide Send
A trait object erases the concrete type, so the compiler cannot see whether the hidden type is Send. You must say so in the type:
use std::thread;
fn main() {
let tasks: Vec<Box<dyn FnOnce() -> i32 + Send>> = vec![
Box::new(|| 1 + 1),
Box::new(|| 20 * 2),
];
let handles: Vec<_> = tasks
.into_iter()
.map(|task| thread::spawn(move || task()))
.collect();
for handle in handles {
println!("{}", handle.join().unwrap());
}
}This prints 2 and then 40. Without + Send, the closure that captures task would not be Send, and spawn would reject it. This mistake is common in task queues and plugin systems that store Box<dyn Fn()>.
Reading the error
When a Send bound fails, the compiler output has a usual shape:
- The headline names the type: `
Rc<i32>cannot be sent between threads safely`. - A note says that the trait
Sendis not implemented for that type. - A note points at the requirement, such as "required by a bound in
spawn". - When the type is buried inside a closure, the output states that the closure is not
Sendbecause it captures the offending variable.
Read the first line for the type, then look at the required by a bound note to find which call imposed the rule. The fix is rarely to touch the bound. It is usually to change the offending type, for example Rc to Arc, or to avoid moving it across the boundary.
Exercise
A function builds a Vec<Rc<String>> on a worker thread and returns it from the closure passed to thread::spawn. Why does this fail, even though the worker thread is the only one that ever touched the Rc values? What are two ways to fix it?
Show answer
The return type Vec<Rc<String>> must be Send because the value moves to the thread that calls join. Vec<T> is Send only when T is, and Rc<String> is not Send, because the compiler checks the type and cannot prove that no other clone exists. One fix is to replace Rc<String> with Arc<String>, which has an atomic count. The other is to return Vec<String> and build any Rc values on the receiving thread.
Exercise
You store jobs as Vec<Box<dyn FnOnce()>> and try to run each one with thread::spawn(move || job()). The compiler rejects it. What change to the type fixes it, and why?
Show answer
Change the element type to Box<dyn FnOnce() + Send>. A trait object hides its concrete type, so the compiler cannot tell whether the closure inside is Send. Adding + Send requires every closure placed in the box to be Send, and that makes the captured job satisfy the bound on spawn.