Skip to content
>_devvkit
$devvkit learn --librarie tokio-guide

Tokio Guide

[rust][async][concurrency]
Rust
Install
cargo add tokio --features full

Tokio is the async runtime for Rust. Provides I/O, timers, channels, synchronization, and a work-stealing scheduler.

Tasks are green threads — lightweight, spawned with tokio::spawn, multiplexed onto OS threads.

The Tokio stack: tokio (runtime, I/O), tonic (gRPC), axum (HTTP), sqlx (database), tracing (logging).

Setup

Async mainAnnotate entry point.
#[tokio::main]
async fn main() {
    println!("Hello from Tokio");
}

Tasks

Spawn taskRun concurrent work.
let handle = tokio::spawn(async {
    do_work().await
});
handle.await.unwrap();
Join multipleRun tasks concurrently.
let (a, b) = tokio::join!(fetch_users(), fetch_posts());
SelectRace tasks.
tokio::select! {
    result = operation1() => println!("op1: {result}"),
    result = operation2() => println!("op2: {result}"),
}

Async I/O

Read fileAsync file I/O.
let contents = tokio::fs::read_to_string("data.txt").await?;
TCP listenerAsync TCP server.
let listener = TcpListener::bind("127.0.0.1:8080").await?;
loop {
    let (socket, addr) = listener.accept().await?;
    tokio::spawn(handle_client(socket));
}

Channels

mpsc channelMulti-producer, single-consumer.
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
tokio::spawn(async move {
    tx.send("hello").await.unwrap();
});
while let Some(msg) = rx.recv().await {
    println!("got: {msg}");
}

Timers

IntervalPeriodic task.
let mut interval = tokio::time::interval(Duration::from_secs(1));
loop {
    interval.tick().await;
    println!("tick");
}
SleepDelay execution.
tokio::time::sleep(Duration::from_millis(100)).await;

Synchronization

RwLockAsync read-write lock.
use tokio::sync::RwLock;

let data = RwLock::new(vec![1, 2, 3]);
{
    let read = data.read().await;
    println!("len: {}", read.len());
}
{
    let mut write = data.write().await;
    write.push(4);
}