Spawning Tasks: Doing Things Concurrently
7 min read
Welcome back, Rustacean! 🦀
You have mastered the basics of async/await. You know how to make a function pause without blocking the thread. But right now, your code is likely running sequentially—just... asynchronously.
To truly unlock the power of modern hardware (and impress your tech lead), you need to do multiple things at the same time. You need concurrency. You need to spawn tasks.
In this guide, we are going to look at how Tokio handles task creation, why it's different from standard threads, and how to avoid the dreaded compiler errors that haunt the dreams of new async developers.
1. tokio::spawn: Creating Lightweight Green Threads
The Problem: OS Threads are "Heavy"
In standard Rust (std::thread), spawning a thread maps 1:1 to an Operating System thread.
- Memory: Each OS thread allocates a large stack (usually 2MB-8MB).
- Context Switching: Switching between OS threads requires kernel intervention, which is slow (relatively speaking).
If you try to spawn 100,000 OS threads to handle 100,000 websocket connections, your server will likely catch fire (or just run out of RAM) before it serves a single request. 💥
The Solution: Tokio Tasks (Green Threads)
Tokio tasks are "Green Threads."
- Definition: A green thread is a thread of execution that is scheduled by a runtime library (Tokio) rather than the underlying operating system.
- Weight: They are incredibly lightweight. A minimal Tokio task might only take 64 bytes initially (plus the future size).
- Scaling: You can easily spawn hundreds of thousands of tasks on a single machine.
Industry Standard: The M:N Model
Tokio uses an M:N threading model. It spawns M tasks and runs them on N OS threads (usually equal to the number of CPU cores). If a task pauses (awaits), Tokio swaps it out instantly for another task on the same OS thread.
How to Spawn
To run code concurrently, we use tokio::spawn.
Setup (Cargo.toml):
[dependencies]
tokio = { version = "1", features = ["full"] }The Code:
use tokio::time::{sleep, Duration};
#[tokio::main]
async fn main() {
println!("🚀 Launching tasks...");
// Spawn a background task
tokio::spawn(async {
// This code runs concurrently with everything else
for i in 1..=3 {
println!(" 👻 Ghost Task saying: Boo! ({})", i);
sleep(Duration::from_millis(500)).await;
}
});
// The main task continues immediately
for i in 1..=2 {
println!("👤 Main Task working: {}", i);
sleep(Duration::from_millis(750)).await;
}
println!("✅ Main task done. Exiting.");
}What happens here?
tokio::spawntakes aFuture(theasyncblock) and submits it to the Tokio Scheduler.- It returns immediately. It does not wait for the ghost task to finish.
- The main function continues running.
⚠️ Important Fact: When the
mainfunction returns, the Tokio runtime shuts down. Any spawned tasks that are still running are instantly killed (dropped). In the example above, if the "Ghost Task" takes longer than the "Main Task," the Ghost will be cut off mid-sentence.
2. Yielding and Awaiting: The Lifecycle of a Task
The Problem: CPU Hogging
Tokio uses Cooperative Multitasking. This is different from your OS, which uses Preemptive Multitasking.
- Preemptive (OS): The OS forcibly interrupts a thread to let another run.
- Cooperative (Tokio): The task must voluntarily give up control.
If you write a task that calculates digits of Pi for 10 seconds without .awaiting, you literally hijack the OS thread. No other tasks on that thread can run. This is called "blocking the runtime."
The Solution: The .await Point
Whenever you call .await, you are essentially saying to the Tokio scheduler: "I am waiting for data (IO/Timer). You can use this CPU thread for someone else now."
Visualizing the Lifecycle
- Poll: Tokio starts executing your task.
- Running: Your code runs synchronously (CPU work).
- Await: You hit
.awaiton something that isn't ready (like a network request orsleep). - Yield: The task saves its state and "yields" execution back to the scheduler.
- Wake: When the resource is ready (data arrived), the task notifies the scheduler: "I'm ready to continue!"
The "Don't Do This" Example:
tokio::spawn(async {
// ⛔️ BAD PRACTICE
// This loops forever without yielding.
// It will starve other tasks on this thread.
loop {
// Doing heavy math...
}
});The Fix:
If you have heavy CPU work, use tokio::task::spawn_blocking or yield manually:
tokio::spawn(async {
loop {
// Do a little bit of work...
// Manual Yield: "I'm nice, let others run."
tokio::task::yield_now().await;
}
});3. JoinHandles: Waiting for Results
The Problem: Fire and Forget
In our first example, the ghost task might get killed when main exits. Also, what if the task calculates a value we need? tokio::spawn is "fire and forget" by default.
The Solution: JoinHandle
tokio::spawn returns a JoinHandle<T>. This is a struct that allows you to manage the spawned task. You can:
- Wait for it to finish (Join).
- Get the return value.
- Abort (cancel) the task.
Practical Example
use tokio::time::{sleep, Duration};
#[tokio::main]
async fn main() {
println!("🍕 Ordering Pizza...");
// Spawn the task and capture the handle
let pizza_handle = tokio::spawn(async {
println!(" 👨🍳 Chef: Making dough...");
sleep(Duration::from_millis(1000)).await;
println!(" 👨🍳 Chef: Baking...");
sleep(Duration::from_millis(1000)).await;
return "Pepperoni"; // The task returns a value
});
println!("💻 Coding while waiting...");
// We wait for the task to finish here
let result = pizza_handle.await;
match result {
Ok(pizza_name) => println!("✅ Pizza is here: {}!", pizza_name),
Err(e) => println!("❌ The chef panicked or task cancelled: {:?}", e),
}
}Understanding the Result
Notice pizza_handle.await returns a Result. Why?
- Ok(T): The task finished successfully and returned value
T. - Err(JoinError):
- Panic: The code inside the task crashed (panicked).
- Cancelled: The task was aborted before finishing.
Industry Tip: Always check the
Resultif the task is critical. If a payment processing task panics silently in the background, you might lose money without realizing it.
4. The Send Bound: Why Tasks Need to be Thread-Safe
The Definition
The Send trait in Rust marks a type that is safe to be sent from one thread to another.
The Problem: Work Stealing
Tokio's scheduler is a "work-stealing" scheduler. Even if you spawn a task on OS Thread #1, if OS Thread #1 gets busy, OS Thread #2 might "steal" that task to balance the load.
Because your task can hop between threads at any .await point, everything you hold across an .await point must be Send.
The Common Error
If you try to use non-thread-safe types (like Rc or standard RefCell) across an await, the compiler will scream.
The most famous error: Using std::sync::Mutex incorrectly.
use std::sync::Mutex;
// ❌ THIS WILL NOT COMPILE
async fn bad_mutex() {
let data = Mutex::new(0);
// We lock the mutex
let guard = data.lock().unwrap();
// We await while holding the lock
// PROBLEM: std::sync::MutexGuard is NOT Send!
// You cannot carry it across threads.
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
println!("Data: {}", *guard);
}The Solution
You have two main options in the industry:
Option 1: Use Tokio's Mutex
Tokio provides an async-aware Mutex. Its guard is Send, so it can be held across await points.
use tokio::sync::Mutex; // Note the import
use std::sync::Arc;
#[tokio::main]
async fn main() {
// Wrap in Arc to share ownership across tasks
let db = Arc::new(Mutex::new(0));
let db_clone = db.clone();
tokio::spawn(async move {
// Lock the async mutex
let mut guard = db_clone.lock().await;
*guard += 1;
// The lock is held here during the wait, blocking other tasks
// that want THIS lock, but not blocking the thread.
});
}Option 2: Restrict the Scope (Preferred)
Don't hold locks across awaits if you don't have to. It reduces contention.
use std::sync::Mutex; // Standard Mutex is fine here!
async fn good_mutex() {
let data = Mutex::new(0);
{
// Lock, modify, and DROP the guard immediately
let mut guard = data.lock().unwrap();
*guard += 1;
} // Guard is dropped here
// Now we await safely because we aren't holding the non-Send guard
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
}5. Summary
- Spawn often: Use
tokio::spawnto run independent units of work. It is cheap and fast. 'staticLifetime: Spawned tasks must own their data (usually viamoveblocks orArc). References generally can't live long enough.- Don't Block: Never perform heavy CPU computation or blocking IO (std::fs) inside a standard async task.
- Join Handles: Use handles to wait for completion and catch panics.
- Send Bound: If you see "cannot be sent between threads safely," check if you are holding a weird type (like a standard Mutex guard) across an
.await.
You are now ready to juggle tasks like a circus performer. Go forth and conquer the concurrency! 🎪
References & Further Reading
Challenge
Task: Implement a Concurrent Worker Pool
You are tasked with building a function process_items_concurrently that simulates a worker pool processing a shared list of items. This function will receive a number of workers to spawn and a vector of u32 items.
Your goal is to use tokio::spawn to create multiple asynchronous tasks (workers). These workers must safely and concurrently process all items from the shared vector.
Requirements:
- The input
Vec<u32>of items must be shared safely among all worker tasks. You will need to wrap it in anArc<Mutex<T>>. - Spawn a number of worker tasks equal to the
num_workersparameter. - Each worker task should run a loop. In each iteration, it should:
a. Acquire a lock on the shared item list.
b. Try to.pop()one item off the vector.
c. Crucially, release the lock immediately after the pop operation.
d. If an item was successfully popped, simulate processing it by awaiting atokio::time::sleepfor 10 milliseconds.
e. Keep a local count of the items it has processed. - When the shared item list is empty, the worker task should exit its loop and return the total count of items it processed.
- The main
process_items_concurrentlyfunction must collect theJoinHandlefor each worker task it spawns. - After spawning all workers, the function must wait for all of them to complete their work.
- Finally, it should sum the processing counts returned from all workers and return this total sum as a
u32.
Expected result
Your code should correctly implement the concurrent worker pattern.
- It must use
Arc<Mutex<Vec<u32>>>to allow multiple tasks to safely access and modify the shared list of items. - It must spawn the correct number of tasks specified by
num_workers. - Each task's implementation must correctly scope the
MutexGuard. The lock must be acquired, an item popped, and the lock must be released before thetokio::time::sleep(...).awaitcall. Holding a standardMutexGuardacross an.awaitpoint would result in a compiler error because it is notSend. - The function must collect all
JoinHandles and correctlyawaittheir completion to gather the processing count from each worker. - The final returned value must be the sum of the counts from all workers, which should equal the total number of items initially in the vector (500 in the provided
mainfunction).
The final println! in main should show that the number of initial items matches the total items processed.