Sub topic 3
Why `thread::spawn` Requires `Send` and `'static`
This chapter assumes ownership, borrowing, lifetimes, traits, closures, and basic thread::spawn.
`Send` and `'static`
thread::spawn may let a new thread outlive the function that created it. Therefore, the closure must own values that are safe to move between threads.
Sendmeans a value can be transferred to another thread.'staticmeans the value contains no borrowed data that could expire before the new thread finishes.
'static does not mean the value must live forever. An owned String is usually 'static because it owns its contents.
use std::thread;
fn main() {
let message = String::from("hello");
let handle = thread::spawn(move || {
println!("{message}");
});
handle.join().unwrap();
}The move closure owns message. Without ownership, a reference to a local variable might become invalid.
Scoped threads: borrowing without `Arc`
thread::scope guarantees that spawned threads finish before the scope ends. This lets closures borrow local data safely.
use std::thread;
fn main() {
let data = vec![1, 2, 3];
thread::scope(|scope| {
let worker = scope.spawn(|| data.iter().sum::<i32>());
println!("sum = {}", worker.join().unwrap());
});
}Use scoped threads when the borrowed data should remain local. Use Arc when ownership must outlive the current scope.
Reading errors and fixing unsafe implementations
An error mentioning Rc<T> is not Send means ownership cannot cross the thread boundary. Replace Rc with Arc for shared ownership. Replace Cell or RefCell with Mutex, RwLock, or atomics when multiple threads access the value.
A manual implementation is justified only when the type's invariants really guarantee thread safety. The bounds must describe the contained data:
struct OwnedPtr<T> {
ptr: *mut T,
}
unsafe impl<T: Send> Send for OwnedPtr<T> {}
unsafe impl<T: Sync> Sync for OwnedPtr<T> {}This is unsafe because the compiler cannot verify that the raw pointer is uniquely owned and correctly synchronized. A wrong implementation can create undefined behavior.
Opting out and async futures
A type can deliberately opt out of both traits by containing a raw-pointer marker:
use std::marker::PhantomData;
struct LocalOnly<T> {
value: T,
_not_thread_safe: PhantomData<*const ()>,
}An async future is Send only when every value stored across an .await is Send. Holding an Rc across .await makes the future unsuitable for a multithreaded executor. Use Arc, or drop the Rc before awaiting.
Exercise
Why can a scoped thread borrow a local vector when thread::spawn cannot?
Show answer
The scope guarantees that the thread finishes before the vector goes out of scope.