Sub topic 3
Send: Moving Values to Another Thread
This chapter assumes you know ownership and move closures, trait bounds, and the basics of thread::spawn and JoinHandle.
What Send promises
Send is a marker trait, which means it has no methods. If a type T implements Send, a value of T can be moved to another thread, and that thread can use it and drop it.
The trait speaks only about ownership transfer. Sharing a reference between threads is a separate question, covered by Sync in the next chapter.
Where the compiler checks it
The signature of thread::spawn contains the check:
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,The closure F must be Send, and so must its return value T. A closure is Send when every value it captures is Send. A move closure captures by value, so those values travel to the new thread.
A value that can move
String owns its heap buffer and nothing else has a pointer to it. Moving it to another thread is safe, so String is Send.
use std::thread;
fn main() {
let name = String::from("worker");
let handle = thread::spawn(move || {
println!("hello from {}", name);
name.len()
});
println!("length = {}", handle.join().unwrap());
}This prints hello from worker and then length = 6. The closure owns name, and the return value usize is also Send.
A value that cannot move
Rc<T> counts its owners with a plain, non-atomic integer. Suppose two threads each held a clone and both changed the count at once. The count could become wrong, and the value could be freed too early or never freed. Rust prevents this by making Rc<T> not Send.
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 does not compile. The compiler reports that Rc<i32> cannot be sent between threads safely, and it adds that the trait Send is not implemented for Rc<i32>. The note also says the bound is required by thread::spawn.
The fix is to use Arc<T>, which updates its count atomically.
Reading the rule in practice
- Owned data such as
String,Vec<i32>andBox<T>isSendwhen its contents areSend. - Primitive numbers and
boolareSend. Rc<T>and raw pointers are notSend.MutexGuardis notSend. On some platforms a lock must be released by the thread that took it.- A struct is
Sendonly if all of its fields are. One non-Sendfield makes the whole struct non-Send.
The 'static bound is a separate requirement. It prevents a spawned thread from borrowing locals that might be gone when the thread runs. A later chapter covers it.
Exercise
A struct holds a String, a Vec<u8> and an Rc<u32>. You move it into a closure passed to thread::spawn. Does it compile, and which type is responsible?
Show answer
It does not compile. A struct is Send only if all of its fields are Send. The Rc<u32> field is not Send, so the whole struct is not Send. Replacing Rc<u32> with Arc<u32> fixes it.