ScriptsApr 12, 2026·1 min read

Tokio — Async Runtime for Reliable Rust Applications

Tokio is a runtime for writing reliable asynchronous applications with Rust. Provides async I/O, networking, scheduling, and timers. The foundation of most async Rust projects including Axum, Hyper, Tonic, and the broader Rust web ecosystem.

SC
Script Depot · Community
Quick Use

Use it first, then decide how deep to go

This block should tell both the user and the agent what to copy, install, and apply first.

# Cargo.toml
[dependencies]
tokio = { version = "1", features = ["full"] }
use tokio::time::{sleep, Duration};
use tokio::net::TcpListener;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

#[tokio::main]
async fn main() {
    // Spawn concurrent tasks
    let handle = tokio::spawn(async {
        sleep(Duration::from_millis(500)).await;
        println!("Task done");
    });

    // TCP echo server
    let listener = TcpListener::bind("127.0.0.1:8080").await.unwrap();
    println!("Listening on :8080");

    loop {
        let (mut socket, _) = listener.accept().await.unwrap();
        tokio::spawn(async move {
            let mut buf = [0; 1024];
            let n = socket.read(&mut buf).await.unwrap();
            socket.write_all(&buf[..n]).await.unwrap();
        });
    }
}
Intro

Tokio is the most popular asynchronous runtime for Rust. It provides building blocks for writing network applications: async I/O, timers, a multi-threaded work-stealing scheduler, channels, and synchronization primitives. Nearly every async Rust project depends on Tokio — it is the foundation of Axum, Hyper, Tonic (gRPC), reqwest, and more.

What Tokio Does

  • Multi-threaded scheduler — work-stealing for parallel async tasks
  • Async I/O — TCP, UDP, Unix sockets, named pipes
  • Timers — sleep, interval, timeout
  • Channels — mpsc, oneshot, broadcast, watch
  • Sync primitives — Mutex, RwLock, Semaphore, Notify (async-aware)
  • Task spawning — lightweight green threads
  • Runtime — configurable (multi-thread or current-thread)
  • Tracing — integrated with tokio-console for debugging

Architecture

Work-stealing scheduler: multiple OS threads each maintain a local task queue. When idle, a thread steals tasks from others. Each task is a Future that the runtime polls. I/O is backed by epoll (Linux), kqueue (macOS), or IOCP (Windows) via the mio crate.

Comparison

Runtime Multi-thread I/O
Tokio Work-stealing mio
async-std Work-stealing async-io
smol Work-stealing async-io
monoio Thread-per-core io_uring

常见问题 FAQ

Q: 什么时候用 Tokio? A: 任何需要异步 I/O 的 Rust 项目——web server、gRPC、数据库客户端、CLI 工具的并发请求。

Q: 和 async-std 比? A: Tokio 生态最大、维护最活跃、性能最佳。async-std 更接近 std API 但社区较小。

来源与致谢 Sources

Discussion

Sign in to join the discussion.
No comments yet. Be the first to share your thoughts.

Related Assets