Sub topic 6
Choosing and starting a runtime with Tokio
This chapter assumes you know Rust ownership and borrowing, traits and generics, closures and move, Result and ?, and how to add a dependency with feature flags in Cargo. You should also know the earlier chapters' ideas: an async fn returns a future, and a future does nothing until something polls it.
Why a runtime is needed
A future is only a value that can be polled. Something must call poll on it, and call it again when the future is ready to make progress. That something is an executor. Rust's standard library defines Future, Poll, Context, and Waker, but it ships no executor, no timers, and no network I/O.
A runtime bundles the pieces you need:
- An executor that schedules and polls tasks.
- A reactor (also called the I/O driver) that watches the operating system for socket and file events and wakes the right task.
- A timer driver that wakes tasks when a deadline passes.
- Utilities such as channels, locks, and a pool for blocking work.
Because the language does not pick one, you choose a runtime as a library. This is why fn main cannot be async on its own: nothing would poll the future it returns.
Choosing a runtime
Tokio is the most widely used runtime and the one this tutorial uses. Other options exist, and the choice matters because runtime-specific types (timers, sockets, spawn) usually do not work across runtimes.
| Runtime | Typical use | Notes |
|---|---|---|
| Tokio | Network services, most of the ecosystem (hyper, axum, tonic, reqwest) | Multi-threaded work-stealing scheduler by default |
| async-std | General async code with a std-like API | Smaller ecosystem than Tokio |
| smol | Small, simple runtime | Easy to embed |
| Embassy | Embedded devices without an operating system | `no_std` |
Pick Tokio unless a library you depend on or your platform dictates otherwise. If most of your dependencies already require Tokio, mixing in a second runtime adds friction.
Adding Tokio to a project
Tokio splits its features behind Cargo feature flags to keep compile times and binary size down. For learning, enable everything:
[dependencies]
tokio = { version = "1", features = ["full"] }In a real application, enable only what you use. Common flags are rt (the executor), rt-multi-thread (the multi-threaded scheduler), macros (#[tokio::main], join!, select!), time, net, fs, io-util, and sync. A missing flag shows up as a compile error such as "cannot find macro main in crate tokio" or a missing tokio::time module.
Starting the runtime with `#[tokio::main]`
The attribute macro #[tokio::main] turns an async fn main into an ordinary fn main that builds a runtime and blocks on your future:
use std::time::Duration;
use tokio::time::sleep;
async fn greet(name: &str) -> String {
sleep(Duration::from_millis(100)).await;
format!("Hello, {name}!")
}
#[tokio::main]
async fn main() {
let message = greet("Ferris").await;
println!("{message}");
}The macro expands to roughly the following. Writing it out once makes clear that nothing special happens:
use std::time::Duration;
use tokio::time::sleep;
async fn greet(name: &str) -> String {
sleep(Duration::from_millis(100)).await;
format!("Hello, {name}!")
}
fn main() {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
let message = greet("Ferris").await;
println!("{message}");
})
}block_on takes a future, polls it on the current thread until it completes, and returns its output. It is the bridge from synchronous code into async code. The enable_all call turns on the I/O and time drivers. Without them, calls such as sleep panic with a message that says no timer is running.
Multi-thread versus current-thread
Tokio offers two scheduler flavors.
The multi-thread flavor is the default. It starts a pool of worker threads, one per CPU core, and moves tasks between them using work stealing: an idle worker takes tasks from a busy worker's queue. Tasks may run on any worker, so they must be Send. The next chapters return to why.
The current-thread flavor runs every task on the thread that calls block_on. It has less overhead, tasks need not be Send when you use local-task APIs, and execution order is easier to reason about. Select it like this:
#[tokio::main(flavor = "current_thread")]
async fn main() {
println!("single-threaded runtime");
}You can also set the worker count of the multi-thread flavor:
#[tokio::main(flavor = "multi_thread", worker_threads = 2)]
async fn main() {
println!("two worker threads");
}Building the runtime yourself
The macro is convenient, but a manual Builder gives control. This is useful when you want a runtime inside a larger synchronous program, need custom thread names, or want to handle build errors instead of panicking.
use std::time::Duration;
use tokio::runtime::Builder;
use tokio::time::sleep;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let rt = Builder::new_multi_thread()
.worker_threads(4)
.thread_name("my-worker")
.enable_all()
.build()?;
let answer = rt.block_on(async {
sleep(Duration::from_millis(50)).await;
42
});
println!("answer = {answer}");
Ok(())
}A Runtime value owns its threads. When you drop it, Tokio shuts the runtime down: it stops driving tasks and waits for worker threads. Tasks that are still unfinished at that point are dropped, not completed. If you need a task to finish, await its JoinHandle before main returns.
What `#[tokio::main]` does not do
Several mistakes come up often.
- Calling
block_oninside a runtime. CallingRuntime::block_onorHandle::block_onfrom code already running on a Tokio worker panics with "Cannot start a runtime from within a runtime". Use.awaitinstead. If you must call async code from a blocking context, do it from a thread started byspawn_blockingand use aHandle. - Forgetting the macro. An
async fn mainwithout#[tokio::main]fails to compile, becausemainmay not beasync. - Using Tokio types without a runtime.
tokio::spawnandtokio::time::sleeppanic with "there is no reactor running" if called outside a runtime context. - Creating a runtime per request. A runtime is expensive to build. Create one at startup and share it.
A runtime does not make blocking code safe. If a task calls std::thread::sleep or does heavy computation without yielding, it holds a worker thread. Later chapters cover spawn_blocking, which solves this.
How a runtime starts a program
Entering the runtime from outside
Sometimes a non-async thread needs to start tasks on a running runtime. A Handle is a cheap, cloneable reference to the runtime for this purpose.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let handle = tokio::runtime::Handle::current();
let thread = std::thread::spawn(move || {
let task = handle.spawn(async {
sleep(Duration::from_millis(50)).await;
"done on the runtime"
});
handle.block_on(task).unwrap()
});
let text = tokio::task::spawn_blocking(move || thread.join().unwrap())
.await
.unwrap();
println!("{text}");
}The plain OS thread uses Handle::block_on, which is allowed because that thread is not a runtime worker. The main task waits through spawn_blocking so it does not hold a worker while joining the thread.
Summary of decisions
- Use Tokio unless you have a reason not to, and enable only the features you need in production.
- Use
#[tokio::main]for ordinary applications. - Use
flavor = "current_thread"for simple tools, tests, or when you want fewer threads. - Use
Builderwhen you embed async code in a synchronous program or need custom configuration. - Keep one runtime per process in most cases.
Exercise
A colleague writes async fn main() with no attribute and calls tokio::time::sleep(...).await inside it. The program does not compile. Why, and what are two ways to fix it?
Show answer
main cannot be async by itself, because nothing would poll the future it returns. Fix 1: add #[tokio::main] above async fn main, which builds a runtime and calls block_on. Fix 2: write a normal fn main that builds a runtime with tokio::runtime::Builder (for example Builder::new_multi_thread().enable_all().build()?) and calls rt.block_on(async { ... }). Either way, the time and rt features of Tokio must be enabled.
Exercise
Your program starts with #[tokio::main] and spawns a task with tokio::spawn, but main returns before the task prints anything. What happens to the task, and how do you make sure it finishes?
Show answer
When main returns, the runtime is dropped and unfinished tasks are dropped with it, so the task may never run to completion. Keep the JoinHandle returned by tokio::spawn and await it (handle.await.unwrap()) before main ends.