Sub topic 5
Choosing a runtime flavor and worker threads
This chapter assumes you can start a runtime with #[tokio::main] and spawn tasks with tokio::spawn. It also assumes you know that spawned tasks must be Send + 'static. You should be comfortable with Cargo features and with std::thread.
#[tokio::main] hides a decision: how many OS threads run your tasks, and how tasks move between them. Tokio calls the two answers runtime flavors. This chapter explains both, how to configure them, and which one to pick.
The two flavors
A Tokio runtime comes in two flavors.
- multi_thread runs a pool of worker threads. Each worker has its own task queue. An idle worker steals tasks from a busy one, so work spreads across cores. This is the default for
#[tokio::main]. - current_thread runs every task on one thread, the thread that calls
block_on. There is no pool and no stealing. Tasks take turns whenever one reaches an.awaitthat returnsPending.
Both flavors are cooperative. A task only gives up its thread at an .await. The flavors differ in how many threads can make progress at once.
Selecting a flavor with the macro
Pass flavor to the attribute. The first program runs everything on one thread:
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main(flavor = "current_thread")]
async fn main() {
let mut handles = Vec::new();
for i in 0..3 {
handles.push(tokio::spawn(async move {
sleep(Duration::from_millis(50)).await;
println!("task {i} on {:?}", std::thread::current().id());
}));
}
for h in handles {
h.await.unwrap();
}
}All three lines print the same ThreadId. The three sleeps still overlap, so the program finishes in about 50 ms. Concurrency does not require parallelism. One thread can interleave many tasks that spend their time waiting.
To get a pool with a fixed size, write #[tokio::main(flavor = "multi_thread", worker_threads = 4)].
Cargo features
The flavors depend on Cargo features. If you use the wrong set, you get a compile error from the macro.
[dependencies]
# Everything, convenient while learning:
tokio = { version = "1", features = ["full"] }
# Or a minimal single-threaded setup:
# tokio = { version = "1", features = ["rt", "macros", "time", "net", "io-util"] }rtprovides the current-thread runtime.rt-multi-threadadds the multi-thread runtime.macrosprovides#[tokio::main]and#[tokio::test].
If you enable macros and rt but not rt-multi-thread, a bare #[tokio::main] fails to compile, because the default flavor is unavailable. Ask for current_thread explicitly in that case.
Building a runtime by hand
The attribute is shorthand. #[tokio::main] expands to roughly "build a runtime, then block_on the body of main". When you need more control, use tokio::runtime::Builder:
use tokio::runtime::Builder;
fn main() {
let runtime = Builder::new_multi_thread()
.worker_threads(2)
.thread_name("my-worker")
.enable_all()
.build()
.unwrap();
runtime.block_on(async {
let handles: Vec<_> = (0..4)
.map(|i| {
tokio::spawn(async move {
let thread = std::thread::current();
println!("task {i} on {:?}", thread.name());
})
})
.collect();
for h in handles {
h.await.unwrap();
}
});
}Each line prints Some("my-worker"). The tasks can land on either of the two workers. The order of the lines can change from run to run.
enable_all() turns on the I/O driver and the timer driver. If you forget it, sleep and TcpListener::bind panic at runtime with a message saying the driver is not enabled. The #[tokio::main] macro enables both for you.
Use the builder when you need any of these:
- A named or sized thread pool.
- Two runtimes in one process, for example one for network I/O and one for background work.
- A runtime created inside a library or inside synchronous code.
Worker threads
With the multi-thread flavor, the default worker count equals the number of CPU cores that the process can see. You can override it in three ways:
worker_threads = Non the attribute..worker_threads(N)on the builder.- The
TOKIO_WORKER_THREADSenvironment variable. It applies only when the code does not set a count explicitly.
Tokio also has a separate blocking pool. It runs spawn_blocking closures and some file-system calls. It is not part of the worker count. It starts with no threads, grows on demand, and is capped by max_blocking_threads, which defaults to 512.
The worker count is a throughput setting, not a concurrency limit. Tens of thousands of tasks can share two workers. More workers help only when tasks have CPU work to do in parallel. In containers, check what the process sees. Older runtimes read the host core count and ignore a CPU quota, which can create more workers than your limit allows.
What changes between flavors
| Concern | multi_thread | current_thread |
|---|---|---|
| Threads running tasks | N workers | The calling thread only |
| Parallel CPU use | Yes | No |
| `tokio::spawn` requires `Send` | Yes | Yes |
| `spawn_local` with `LocalSet` | Works | Works, the usual home for `!Send` futures |
| `block_in_place` | Allowed | Panics |
| Effect of one blocking task | Stalls one worker | Stalls the whole runtime |
| Default in `#[tokio::test]` | No | Yes |
Failure modes
Blocking on a current-thread runtime. Suppose a task calls std::thread::sleep or does a long computation. No other task can run, so timers, sockets and the main future all wait. On a multi-thread runtime the same bug hurts less: only one worker is stuck, so the problem hides until all workers are blocked. Treat both as bugs and move such work to spawn_blocking, as the later chapter on blocking work explains.
Assuming worker_threads(1) equals current_thread. It does not. A one-worker multi-thread runtime still runs tasks on a worker thread, separate from the thread that called block_on. It also allows block_in_place. The current_thread runtime runs tasks on the calling thread and needs no pool.
Tests that pass on one flavor. #[tokio::test] uses current_thread by default. A test can pass there and then deadlock or misbehave in production. For example, a task might block waiting on another task that needs a second worker. Use #[tokio::test(flavor = "multi_thread", worker_threads = 2)] when behavior depends on parallelism.
Nested runtimes. Calling block_on from inside an async context panics with "Cannot start a runtime from within a runtime". Use .await instead, or spawn_blocking to cross into synchronous code.
Choosing a flavor
Start with the default multi-thread runtime for servers and anything that mixes I/O with some CPU work. Choose current_thread when one of these applies:
- The program is small, such as a CLI tool, and spawning a pool costs more than it saves.
- You need
!Sendstate and plan to useLocalSet. - You want deterministic scheduling, for example in tests that use paused time.
- You run one runtime per core yourself and pin each to a thread.
Measure before tuning the worker count. The default is correct for most services. Lower it when the process shares a machine with other work. Raise it only after profiling shows idle cores and queued tasks.
Exercise
A test passes under plain #[tokio::test] but hangs in production on a multi-thread runtime. Name one flavor-related cause and the change that would let the test reproduce it.
Show answer
#[tokio::test] defaults to currentthread, so every task shares one thread and timing differs from production. A hang can come from code that depends on tasks running in parallel, or from blocking calls that only stall one worker at a time. Change the test to #[tokio::test(flavor = "multithread", worker_threads = 2)] so it runs on real worker threads.
Exercise
You build a runtime with Builder::newmultithread().workerthreads(2).build() and then call tokio::time::sleep inside blockon. The program panics. What is missing, and what does the #[tokio::main] macro do differently?
Show answer
The builder is missing .enableall(), or at least .enabletime(), so the timer driver is not running. The #[tokio::main] macro enables all drivers for you.