skip to content

In Rust, what does `std::thread::spawn` return, and what happens to the spawned thread if `main` returns without joining it?

level: juniorimportance: must knowfreq 80%

answer

  1. an owned handle per thread
  2. join blocks, then hands back a Result
  3. dropping the handle detaches
  4. process exit ends every thread

basics

~20 s

thread::spawn returns a JoinHandle<T> for the closure's result; join() waits and gives Ok(T) or an Err carrying the panic payload. Dropping the handle detaches the thread, and once main returns the process exits, stopping any thread still running.

solid answer

~40 s

`thread::spawn(f)` starts an OS thread running the closure and returns a `JoinHandle<T>`, where `T` is the closure's return type. Calling `handle.join()` blocks until that thread finishes and returns `std::thread::Result<T>`: `Ok(value)` on success, or `Err` holding the panic payload if the thread panicked. `join` takes `self`, so each thread is joined at most once. If you drop the handle, the thread is **detached**: it keeps running, but nothing can wait for it any more. And when `main` returns, the whole process exits, so a detached thread that has not finished is simply stopped mid-work. On mainstream targets rustc does not warn when you discard a `JoinHandle`, so the fix is a habit: keep the handles and join them before `main` ends. The closure is usually `move`, because `spawn` requires it to own what it uses.

code

rust · 21 lines
rust
use std::thread;
use std::time::Duration;

fn main() {
    let records = vec!["GET /a", "POST /b", "GET /c"];

    // `move` hands the Vec to the new thread; the closure returns a usize.
    let handle: thread::JoinHandle<usize> = thread::spawn(move || {
        records.iter().filter(|r| r.starts_with("GET")).count()
    });

    // join blocks until the thread ends and yields thread::Result<usize>.
    let gets = handle.join().expect("worker panicked");
    println!("GET lines: {gets}");

    // Dropping the handle detaches this thread.
    thread::spawn(|| {
        thread::sleep(Duration::from_millis(200));
        println!("never printed: main has already returned");
    });
}

go deeper

for a junior

Recall the shape: spawn returns a JoinHandle<T>, join waits and returns a Result with the closure's value or the panic. Keep handles and join them before main returns.

for a middle

Explain that dropping the handle detaches rather than cancels, that main's return ends the process, and that join consumes the handle and orders the thread's work before the caller's next line.

for a senior

Show how you would catch an unjoined worker in review, since rustc stays silent, and how you decide whether a worker panic should propagate through expect or be logged and survived.

for a principal

Frame detached threads as a shutdown-correctness question: which background work may be lost at exit, and how the service guarantees flushes and cleanup run before main returns.

## What `thread::spawn` gives you `std::thread::spawn` asks the operating system for a new thread and runs a closure on it. Its signature is the whole story in miniature: ```rust pub fn spawn<F, T>(f: F) -> JoinHandle<T> where F: FnOnce() -> T + Send + 'static, T: Send + 'static, ``` - **`F: FnOnce() -> T`** means the closure runs exactly once and may return a value of any type `T`. - **`JoinHandle<T>`** is the return value: an owned permission to wait for that particular thread and collect its `T`. - The `Send + 'static` bounds say the closure and its result must be safe to move between threads and must not borrow short-lived locals. Why that is, and the E0373 error you get when a closure borrows a local `Vec`, belong to the lesson on `'static` lifetimes; in practice it is why you write `thread::spawn(move || ...)` and hand the data over. `spawn` itself panics if the OS cannot create the thread (the code calls `expect("failed to spawn thread")`); `thread::Builder::spawn` is the variant that returns an `io::Result` instead. ## Joining: waiting and collecting the result `JoinHandle::join(self)` blocks the calling thread until the spawned one finishes, then returns **`std::thread::Result<T>`**, an alias for `Result<T, Box<dyn Any + Send + 'static>>`: 1. If the closure returned normally, you get `Ok(value)`, so a worker can hand back a count, a `Vec` or a parsed struct. 2. If the closure panicked, the panic unwound that thread only, and `join` returns `Err(payload)`, the value given to `panic!`. 3. If the thread had already finished, `join` returns immediately. Because `join` takes `self` by value, the handle is consumed; calling `join` twice on the same handle is a compile error (E0382, use of moved value). The docs also promise that everything the thread did happens-before the code after `join` returns, so reading its results afterwards needs no extra synchronisation. `JoinHandle::is_finished` checks without blocking. | What you do with the handle | Effect on the thread | |---|---| | `handle.join()` | wait for it, get `Ok(T)` or `Err(payload)` | | `handle.is_finished()` | ask without blocking; join later | | drop it (or never bind it) | thread is **detached** and keeps running | ## Detaching, and what happens when `main` returns The standard library says it directly: if the join handle is dropped, the spawned thread is implicitly **detached** and can no longer be joined. Dropping the handle does **not** stop, cancel or interrupt the thread. It only throws away your ability to wait for it. The second half of the story is the main thread. When `main` returns, the Rust program ends and the process exits; the Rust Book puts it as "all spawned threads are shut down, whether or not they have finished running". A detached thread that was halfway through writing a compacted log file is stopped wherever it is. Its remaining statements do not run, so output it has not yet flushed and values it has not yet dropped are lost with it. Note what rustc does **not** do here. On mainstream targets `JoinHandle` is not marked `#[must_use]`, so a bare `thread::spawn(...);` statement compiles with no warning at all. Forgetting to join is a logic bug the compiler will not point at. ## Spawned threads that outlive their caller Only the main thread's exit ends the process. A thread spawned from another worker can outlive that worker: if worker A spawns B and returns, B keeps running until it finishes or `main` exits. That is also why `spawn` insists on `'static`: std cannot know when the thread will end, so nothing it holds may point into a stack frame that could disappear first. When you want threads that borrow locals and are guaranteed to finish before a function returns, `std::thread::scope` is the tool, covered in its own question. ## Habits that avoid the classic bugs - **Keep every handle** in a `Vec<JoinHandle<T>>` and join them all before `main` ends. - **Return results through `join`** instead of printing from the worker and hoping it ran. - **Decide what a worker panic means**: `.join().expect("worker panicked")` re-panics on the caller, while a `match` on the `Err` can log it and carry on. - **Detach only on purpose**, for work that is genuinely fine to lose at exit, such as a best-effort metrics flush.

  • Does rustc warn you when you discard the `JoinHandle` returned by `thread::spawn`?
    No. On mainstream targets `JoinHandle` carries no `#[must_use]` attribute, so `thread::spawn(work);` as a bare statement compiles silently and detaches the thread. Nothing in the type system forces a join; it is a review habit, often enforced by collecting handles in a `Vec` and joining them in a loop.
  • Can you call `join` twice on the same `JoinHandle`?
    No. `JoinHandle::join` takes `self` by value, so the first call consumes the handle and a second call is rejected with E0382, use of moved value. If several parts of the code need to know when a thread is done, have the thread send a message or set a flag rather than sharing the handle.
  • How do you check whether a spawned thread has finished without blocking?
    `JoinHandle::is_finished(&self)` returns a `bool` and never blocks. Once it returns `true`, a following `join` returns promptly, so a supervisor loop can poll `is_finished` on each handle and only call `join` on the ones that are done.

  • Spawned threads keep running after main returns, like background daemons.
  • Dropping a JoinHandle cancels or kills the thread.
  • join returns the closure's value directly, so a worker panic crashes the caller.
  • rustc warns whenever a JoinHandle is ignored.
  • A thread must be joined or the program does not compile.