Tokio
Tokio is the most common Rust async runtime. It polls futures, provides async TCP and timers, and spawns tasks onto a pool of worker threads.
Detailed Explanation
The language has futures. It does not have an event loop. Tokio is that loop plus a library of I/O types. #[tokio::main] starts a runtime and block_ons your async fn main. tokio::spawn schedules a 'static + Send future as a task. The multi-thread runtime (the default for #[tokio::main]) steals work across workers. The current-thread runtime is for programs that should not create extra threads.
Tokio's types are the ones you must use on its workers: tokio::fs, tokio::net::TcpListener, tokio::time::sleep, tokio::sync::mpsc. The std counterparts block. Mixing them is the first production bug: a handler that std::fs::reads a large file on the async worker stalls every other connection on that thread. spawn_blocking moves that call to a blocking-thread pool.
Tasks are not OS threads. A waiting task occupies a small allocation, not a megabyte stack. A CPU-heavy loop without an .await still starves the worker; yield with tokio::task::yield_now or move the work to spawn_blocking. JoinHandle awaits the task's result. Dropping the handle does not cancel the task; abort it explicitly or drop a cancellation token.
Behaviours people miss: spawn requires Send. A Rc inside the task will not compile. Use tokio::task::spawn_local on a local-set for !Send futures. select! is in tokio::select. Timeouts are tokio::time::timeout.
When you reach for Tokio: networked services, many sockets, timers. When you reach for std threads: a small parallel CPU job. When you reach for another runtime (async-std, smol): you have a reason; most of the ecosystem assumes Tokio.
The multi-thread runtime moves tasks. A !Send future (one that holds Rc or a thread-local) must live on a LocalSet and spawn_local. Mixing spawn and spawn_local without a local set is a compile error or a runtime panic depending on how you wrote it. Decide the thread model when you choose #[tokio::main], not after the first Rc.
Code Examples
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
tokio::time::sleep(std::time::Duration::from_millis(1)).await;
41 + 1
});
println!("{}", handle.await.unwrap()); // prints: 42
}Common Gotchas
Std blocking I/O on a worker stalls the runtime
Use Tokio I/O or `spawn_blocking`. This is the first thing to check in a "mystery latency" ticket.
`spawn` needs `Send + 'static`
`Rc` and borrowed locals will not compile. `Arc` and owned data will.
Dropping a `JoinHandle` does not stop the task
Call `abort` if cancellation matters.
A tight loop without `.await` is a stuck worker
The scheduler cannot preempt CPU work. Yield or spawn_blocking.