$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 main— Annotate entry point.
#[tokio::main]
async fn main() {
println!("Hello from Tokio");
}Tasks
Spawn task— Run concurrent work.
let handle = tokio::spawn(async {
do_work().await
});
handle.await.unwrap();Join multiple— Run tasks concurrently.
let (a, b) = tokio::join!(fetch_users(), fetch_posts());
Select— Race tasks.
tokio::select! {
result = operation1() => println!("op1: {result}"),
result = operation2() => println!("op2: {result}"),
}Async I/O
Read file— Async file I/O.
let contents = tokio::fs::read_to_string("data.txt").await?;TCP listener— Async 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 channel— Multi-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
Interval— Periodic task.
let mut interval = tokio::time::interval(Duration::from_secs(1));
loop {
interval.tick().await;
println!("tick");
}Sleep— Delay execution.
tokio::time::sleep(Duration::from_millis(100)).await;
Synchronization
RwLock— Async 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);
}