Sub topic 5
Choosing and starting a runtime with Tokio
This chapter assumes you know how to write async fn, how .await works, and that futures are lazy. You should also be comfortable adding dependencies and feature flags in Cargo.
Why a runtime is needed
An async fn returns a future. Nothing polls that future until something does. Rust's standard library defines the Future trait but ships no executor, so you must pick a runtime crate. A runtime provides three things:
- An executor that polls futures and wakes them when they can make progress.
- A reactor that watches the operating system for I/O and timer events.
- Utilities such as timers, networking, channels, and task spawning.
main cannot be async by itself, because nothing would poll the future it returns. A runtime fills that gap.
Choosing a runtime
Tokio is the most widely used runtime and has the largest ecosystem of compatible libraries. Alternatives such as async-std and smol exist. Most web frameworks and database clients target Tokio, so it is the usual default.
Add Tokio to Cargo.toml:
[dependencies]
tokio = { version = "1", features = ["full"] }The full feature enables everything and suits learning. In a real project you can list only the features you use, such as rt-multi-thread, macros, time, and net, to reduce compile time.
Starting the runtime with #[tokio::main]
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 #[tokio::main] attribute rewrites main into a normal function. It builds a runtime and calls block_on with the body of your async main. Roughly, it expands to this:
use std::time::Duration;
use tokio::time::sleep;
fn main() {
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap();
rt.block_on(async {
sleep(Duration::from_millis(100)).await;
println!("Hello, Ferris!");
});
}Writing the builder yourself is useful when you need to configure the runtime, for example to set the number of worker threads or to create the runtime inside a larger synchronous program.
Multi-thread and current-thread flavors
Tokio has two scheduler flavors.
| Flavor | Behavior | Typical use |
|---|---|---|
| Multi-thread (default) | A pool of worker threads, one per CPU core by default. Tasks can move between threads. | Servers and general applications. |
| Current-thread | All tasks run on the thread that calls `block_on`. | Tests, small tools, and code with `!Send` futures. |
Select the flavor in the attribute:
#[tokio::main(flavor = "current_thread")]
async fn main() {
println!("running on one thread");
}You can also set the worker count with #[tokio::main(worker_threads = 4)].
Common errors
- "there is no reactor running, must be called from the context of a Tokio 1.x runtime": you used a Tokio timer or I/O type outside a runtime. Start one with
#[tokio::main]or aRuntime. - "
mainfunction is not allowed to beasync": you wroteasync fn mainwithout the attribute. - "Cannot start a runtime from within a runtime": you called
block_oninside async code. Use.awaitinstead.
Exercise
What does #[tokio::main] turn your async main into, and why is that needed?
Show answer
It turns it into a synchronous main that builds a Tokio runtime and calls block_on on the async body. This is needed because futures do nothing until an executor polls them, and the standard library does not provide one.
Exercise
You are writing a test that uses a future that is not Send. Which Tokio scheduler flavor fits, and how do you request it?
Show answer
The current-thread flavor, because all tasks stay on one thread. Request it with #[tokio::main(flavor = "current_thread")], or #[tokio::test] for tests, which uses current-thread by default.