Sub topic 4
Starting a Tokio runtime with #[tokio::main]
This chapter assumes you know Rust ownership, traits and closures, and basic Cargo use. You should also know what async fn and .await do, and that a runtime polls futures. Here you will start a Tokio runtime and see what #[tokio::main] does for you.
Why main cannot be async by itself
An async fn returns a future. A future does nothing until something polls it. The normal fn main entry point is synchronous, and the language does not supply an executor. Writing async fn main() with no help fails to compile, because nothing would drive the returned future.
The #[tokio::main] attribute fixes this. It rewrites your async fn main into a plain fn main that builds a runtime and blocks on your body.
Adding Tokio
Add the dependency with the features you need. The full feature is convenient while learning.
[dependencies]
tokio = { version = "1", features = ["full"] }In real projects, enable only the features you use, such as rt-multi-thread, macros, time and net. This keeps compile times and binary size down.
A first program
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
println!("starting");
sleep(Duration::from_millis(100)).await;
println!("done");
}The macro expands to roughly the code below. Reading it shows there is no magic.
fn main() {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
println!("starting");
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
println!("done");
})
}block_on runs the future on the current thread until it finishes. The runtime is created first and dropped when main returns.
Returning a Result
main can return a Result, so you can use ? at the top level.
use tokio::net::TcpListener;
#[tokio::main]
async fn main() -> std::io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
println!("listening on {}", listener.local_addr()?);
Ok(())
}If main returns Err, the process prints the error and exits with a non-zero code.
Common errors
- Missing features. If
#[tokio::main]is not found, themacrosfeature is off. If the flavor is missing,rt-multi-threadis off. - Calling Tokio APIs outside a runtime. Functions such as
tokio::spawnorsleeppanic with "there is no reactor running" when called from plain synchronous code that has no runtime context. - Nesting runtimes. Calling
block_onfrom inside async code panics. Use.awaitinstead. - Forgetting
.await. The compiler warns that the future is unused. Without.await, the work never runs.
Building the runtime yourself
Use the macro for most programs. Build the runtime by hand when you need control, such as a custom thread name or a runtime that lives inside a mostly synchronous program.
use tokio::runtime::Builder;
fn main() {
let rt = Builder::new_multi_thread()
.worker_threads(2)
.thread_name("my-worker")
.enable_all()
.build()
.unwrap();
let answer = rt.block_on(async { 6 * 7 });
println!("{answer}");
}Exercise
Why does async fn main() {} fail to compile without #[tokio::main], and what does the attribute generate to fix it?
Show answer
An async fn only returns a future, and the standard entry point has no executor to poll it. #[tokio::main] generates a synchronous fn main that builds a Tokio runtime (multi-thread by default) and calls block_on on your async body.
Exercise
What happens if you call Runtime::block_on from inside code already running on a Tokio runtime, and what should you write instead?
Show answer
It panics, because runtimes cannot be nested on the same thread. Inside async code, use .await on the future.