CodeBlanks Logo Icon CodeBlanks

spawn

Spawn async tasks with tokio::spawn.

spawn

tokio::spawn hands a future to the runtime as an independent task and returns a JoinHandle. Tasks are very light; thousands of them can live at once:

let tutucular: Vec<_> = (1..=3)
    .map(|i| tokio::spawn(async move { i * i }))
    .collect();
for t in tutucular {
    println!("{}", t.await.unwrap());
}

Since a task may run on any of the runtime's threads, the future must be Send + 'static; that is, it must use owned data (async move), not borrows from outside.

The std counterpart

The same pattern is built with operating-system threads using std::thread::spawn. Threads are much heavier than tasks (each has its own stack), but they're the right tool for CPU-heavy work:

use std::thread;

let tutucular: Vec<_> = (1..=3)
    .map(|i| thread::spawn(move || i * i))
    .collect();
let sonuc: Vec<i32> = tutucular.into_iter().map(|t| t.join().unwrap()).collect();

Collecting results in handle order makes the output independent of which thread finishes first.

Practice Parallel squares

Start three thread::spawns for 1..=3, each computing i * i. Collect the results into a vector in handle order with join and print it.

Starter code

main.rs
use std::thread;

fn main() {
    // buraya yaz
}

Sample solution

main.rs
use std::thread;

fn main() {
    let tutucular: Vec<_> = (1..=3).map(|i| thread::spawn(move || i * i)).collect();
    let sonuc: Vec<i32> = tutucular.into_iter().map(|t| t.join().unwrap()).collect();
    println!("{:?}", sonuc);
}

Expected output

[1, 4, 9]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens to the task if you drop the <code>JoinHandle</code> without awaiting it?

  • It keeps running in the background (detached) Correct answer
  • It's cancelled immediately
  • Panic
  • It never starts

Explanation: To cancel, call handle.abort(). With std threads, dropping the JoinHandle also detaches the thread.

2 Start a task

Question
let t = tokio::____(async move { 2 + 2 });
println!("{}", t.await.unwrap());
Answer
let t = tokio::spawn(async move { 2 + 2 });
println!("{}", t.await.unwrap());

Explanation: tokio::spawn runs a future as an independent task.

3 Tool and property

Term Meaning
tokio::spawn Light task
thread::spawn OS thread
handle.await Task result
handle.abort() Cancel the task

All lessons in Advanced