Sub topic 4
Starting a Tokio Runtime with #[tokio::main]
This chapter assumes you know Rust ownership and closures, can add a crate with Cargo, and have read the earlier chapters on futures, polling, and what an executor and reactor do. Here you will see how a Tokio program starts, what the #[tokio::main] attribute does for you, and the errors people hit most often.
Why main cannot be async by itself
The Rust compiler calls fn main() as an ordinary function. An async fn does not run when called. It returns a future, which is a value that does nothing until something polls it. If main were async, the program would produce a future and then exit without running it.
Something has to create a runtime and hand it the future. That is the job of #[tokio::main].
// This does not compile: `main` function is not allowed to be `async`
async fn main() {
println!("never runs");
}Enabling Tokio in Cargo
Tokio is split into feature flags so that you only compile what you use. The macro and the multi-thread runtime each sit behind a feature. For learning, full turns everything on.
[dependencies]
tokio = { version = "1", features = ["full"] }For a real service, list only the features you need, for example rt-multi-thread, macros, time, net, io-util, and sync. A missing feature shows up as an error such as "cannot find attribute main in crate tokio" (the macros feature is absent) or a missing sleep function (the time feature is absent).
The basic program
This is the smallest useful Tokio program. It spawns a task, awaits a timer inside it, and reads the result through the task's JoinHandle.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
sleep(Duration::from_millis(100)).await;
42
});
let value = handle.await.unwrap();
println!("task returned {value}");
}The main function is declared async, and the attribute rewrites it. You write the body as if the runtime already existed.
What the macro expands to
#[tokio::main] is a procedural macro. It renames your async function, then generates a normal synchronous main that builds a runtime and blocks on your future. The expansion is roughly this:
use std::time::Duration;
use tokio::runtime::Builder;
use tokio::time::sleep;
fn main() {
let runtime = Builder::new_multi_thread()
.enable_all()
.build()
.unwrap();
runtime.block_on(async {
sleep(Duration::from_millis(100)).await;
println!("done");
});
}Three parts matter here.
Builder::new_multi_thread()selects the runtime flavor. The default for the macro is the multi-thread flavor, which runs a pool of worker threads.enable_all()turns on the I/O driver (the reactor) and the timer driver. Without them, network calls andsleepwould panic with a message that a driver is not enabled.block_onruns the given future on the current thread until it finishes. It is the bridge from synchronous code into async code.
The main future is not a spawned task
The body of async fn main runs inside block_on, on the thread that started the program. It is not a task created by tokio::spawn. This has two practical effects.
- The main future does not need to be
Sendor'static. It can borrow local variables and hold non-Sendvalues, because it never moves to another thread. - Spawned tasks are separate. They run on worker threads and must satisfy the bounds covered in a later chapter.
A consequence for performance: the main future runs on a thread that is not a worker. If you do heavy work directly in main between awaits, you block only that future, but long stretches without an .await are still a bad habit.
When main returns, the program ends
When block_on returns, the generated main ends, and the runtime is dropped. Dropping the runtime shuts down the worker threads. Tasks that have not finished are cancelled at their next .await, and their destructors run. They do not get to finish their work.
This catches many beginners. The following program prints nothing, because main returns before the spawned task wakes up from its sleep.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
tokio::spawn(async {
sleep(Duration::from_millis(200)).await;
println!("you will not see this");
});
// main returns immediately, the runtime is dropped
}The fix is to await the JoinHandle, or to use a shutdown signal, which a later chapter covers.
Returning errors from main
#[tokio::main] supports main functions that return Result. The error is printed with Debug formatting, and the process exits with a non-zero status code, exactly as with a synchronous main.
use tokio::net::TcpListener;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
println!("listening on {}", listener.local_addr()?);
Ok(())
}Using ? in main keeps startup code short. Binding a port can fail, and you want that failure to end the process with a clear message.
Configuring the macro
The attribute accepts arguments that map to the builder.
| Attribute | Runtime built |
|---|---|
| `#[tokio::main]` | Multi-thread, worker count equals CPU cores |
| `#[tokio::main(flavor = "current_thread")]` | Single-threaded, no worker pool |
| `#[tokio::main(worker_threads = 4)]` | Multi-thread with four workers |
The next chapter compares the flavors in detail. For now, remember that these arguments are shorthand. When you need settings the macro does not expose, such as a thread name or a thread stack size, build the runtime yourself.
Building the runtime by hand
Writing the runtime out gives you full control and is common in libraries, in programs that mix sync and async code, and in programs that must do work before the runtime starts.
use std::time::Duration;
use tokio::runtime::Builder;
use tokio::time::sleep;
fn main() {
let runtime = Builder::new_multi_thread()
.worker_threads(2)
.thread_name("my-worker")
.enable_all()
.build()
.expect("failed to build runtime");
let result = runtime.block_on(async {
let handle = tokio::spawn(async {
sleep(Duration::from_millis(50)).await;
"finished"
});
handle.await.unwrap()
});
println!("{result}");
}Reasons to prefer a manual build include:
- You need to parse command-line arguments or load configuration before choosing the thread count.
- You want to run the runtime in a background thread while the main thread does something else, such as a GUI loop.
- You want to expose a synchronous API that uses async code internally.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| "there is no reactor running, must be called from the context of a Tokio runtime" | Calling `tokio::spawn`, `sleep`, or a socket function from a thread with no runtime | Run the code inside `block_on` or inside a spawned task, or enter the runtime with `runtime.enter()` |
| "Cannot start a runtime from within a runtime" | Calling `block_on` or creating a second `#[tokio::main]` runtime from async code | Use `.await` instead, or move the blocking call to `spawn_blocking` |
| "cannot find attribute `main` in crate `tokio`" | The `macros` feature is not enabled | Add `macros` or `full` to the Tokio features |
| "The `Builder::new_multi_thread` function is not found" | The `rt-multi-thread` feature is not enabled | Add `rt-multi-thread` or `full` |
| Program exits with no output from spawned tasks | `main` returned before the tasks finished | Await the `JoinHandle` values |
Only one runtime per program entry
Calling #[tokio::main] on a function other than main, or building a second runtime inside async code, usually signals a design problem. A program normally has one runtime, created once at the top. Nested runtimes panic when you call block_on inside one, because the worker thread would block while it is needed to drive other futures.
If synchronous code deep in your program needs to call async code, pass a tokio::runtime::Handle to it. A Handle is a cheap, cloneable reference to the running runtime.
use tokio::runtime::Handle;
#[tokio::main]
async fn main() {
let handle = Handle::current();
let joined = std::thread::spawn(move || {
handle.block_on(async { 1 + 1 })
})
.join()
.unwrap();
println!("{joined}");
}This works because the block_on call happens on a plain OS thread, not on a runtime thread. Calling handle.block_on from inside an async task would panic.
Exercise
A program has #[tokio::main] async fn main() that calls tokio::spawn on a task which sleeps for one second and then prints a message. The main function has no other statements after the spawn. Why does the message never appear, and what is the smallest change that makes it appear?
Show answer
The body of main is the future passed to block_on. When it finishes, block_on returns, the generated main ends, and the runtime is dropped, which cancels the sleeping task before it wakes. The smallest fix is to keep the JoinHandle returned by tokio::spawn and call .await on it (for example handle.await.unwrap();), so the main future does not complete until the task has finished.
Exercise
You write #[tokio::main] async fn main() and inside it you call runtime.block_on(...) on a second runtime you built. The program panics at startup. What rule did you break, and what should you use instead?
Show answer
A runtime cannot start another block_on from a thread that is already driving a runtime, because that thread would block while the runtime needs it. Remove the nested runtime and use .await on the future directly. If the code must be synchronous, run it in tokio::task::spawn_blocking, or call Handle::block_on from a plain OS thread.