liveBook · Manning

Spawn

As explained in Learn Rust in a Month of Lunches

spawn is a Rust standard-library function that starts a new thread to execute a supplied closure and returns a handle for that thread.

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

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains scheduling, joining, closure bounds, ownership, and 'static lifetimes without descending into thread-runtime internals.
Examples
Uses printing threads, repeated spawning, JoinHandle joining, and moving a String into a closure.
What it assumes
Assumes basic Rust closures and borrowing, while teaching thread lifetime constraints through compiler feedback.
What you can do after
Apply via std::thread::spawn, capture owned values with move, and wait for completion through JoinHandle.
How it connects
Connects threads with closures, JoinHandle, ownership, borrowing, move, Send, and 'static lifetimes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.