liveBook · Manning

Tokio::task::spawn

As explained in Code Like a Pro in Rust

tokio::task::spawn is a Tokio function that schedules an asynchronous task on the runtime and returns a join handle.

`tokio::task::spawn()` schedules an async task on the Tokio runtime and returns a `JoinHandle`. Use it when a future should run as a separate task rather than waiting for it directly with `.await`. Spawning introduces concurrency and can permit parallel execution, but Tokio chooses where the task runs. section 8.5 section 8.4

Spawn and wait for completion

`fn start() -> tokio::task::JoinHandle<()> { tokio::task::spawn(async { println!("done"); }) }` An ordinary function can return the handle. From an async context, call `start().await` to wait for the task; retain the handle if you may need to abort it. section 8.4

Do not discard the handle when completion matters. A spawned task may not run before the program exits. Spawning also does not guarantee parallelism: with one worker thread, tasks run on that thread. Avoid blocking operations inside ordinary async tasks; use `tokio::task::spawn_blocking()` for blocking work. section 8.4 section 8.5

How Code Like a Pro in Rust covers it

How deep it goes
Explains scheduling, join handles, completion hazards, and worker-thread limits without detailing Tokio’s scheduling internals.
Examples
Contrasts awaited, unexecuted, and fire-and-forget async blocks, then compares spawned tasks with joined futures using sleep.
What it assumes
Assumes Rust familiarity and explains the relevant behavior of async blocks, futures, `.await`, and the Tokio runtime.
What you can do after
Apply it via Tokio to launch a task, await its handle when completion matters, and avoid assuming it runs in parallel.
How it connects
Connects task spawning to futures, `.await`, `JoinHandle`, concurrency, parallelism, and `spawn_blocking()`.

Related concepts

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