spawn is a Rust standard-library function that starts a new thread and gives it a closure to run. It returns a JoinHandle, which lets the main thread wait for the new thread to finish. section 11.6.1
fn main() {
std::thread::spawn(|| {
println!("I am printing something");
});
}
Start with a minimal thread: the closure prints independently, while main may finish before the spawned thread gets to run. section 11.6.1
Thread scheduling is not predictable. If main reaches its end first, the program shuts down and the spawned thread may print nothing or panic while accessing stdout during shutdown. Calling join on the returned handle provides the intended way to wait. section 11.6.1 section 11.7
Moving captured data into a thread
A spawned closure cannot safely borrow a local value because the thread may outlive the function that created it. Add move so the closure takes ownership, then join the handle: std::thread::spawn(move || { println!("{my_string}"); }). The compiler's lifetime error points toward this correction. section 11.6.4
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static,
The signature shows the main requirements: spawn accepts an FnOnce closure, and both the closure and its return value must be Send and 'static. section 11.6.1
