Rust
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.
Exercise 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.
Show example solution
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);
}
Test yourself
-
What happens to the task if you drop the <code>JoinHandle</code> without awaiting it?
- It keeps running in the background (detached)
- It's cancelled immediately
- Panic
- It never starts
Show answer
It keeps running in the background (detached) — To cancel, call handle.abort(). With std threads, dropping the JoinHandle also detaches the thread.
-
Start a task
let t = tokio::____(async move { 2 + 2 });
println!("{}", t.await.unwrap());
Show answer
let t = tokio::spawn(async move { 2 + 2 });
println!("{}", t.await.unwrap());
-
Tool and property
- tokio::spawn
- Light task
- thread::spawn
- OS thread
- handle.await
- Task result
- handle.abort()
- Cancel the task
Next lesson: tokio::sync