Module tokio

Source
Expand description

Asynchronous runtime for writing reliable network applications.


tokio is an asynchronous runtime for the Rust programming language. It provides the building blocks needed for writing network applications without compromising speed.

At a high level, Tokio provides:

  • A multi-threaded, work-stealing based task scheduler
  • A reactor backed by the operating system’s event queue (epoll, kqueue, IOCP, etc.)
  • Asynchronous TCP and UDP sockets
  • Asynchronous filesystem operations
  • Timer and timeout utilities

Tokio is built using the async/await syntax introduced in Rust 1.39. The runtime schedules asynchronous tasks cooperatively, allowing thousands of tasks to run concurrently on a small number of threads.

The Runtime provides the execution environment for async code. Most applications will use the tokio::main macro to set up the runtime, though it can also be constructed manually for more control.

Tokio’s networking primitives like TcpListener and TcpStream are designed to work seamlessly with async/await, making it straightforward to write servers and clients.

§Examples

Creating a simple TCP echo server:

use tokio::net::{TcpListener, TcpStream};
use tokio::io::{AsyncReadExt, AsyncWriteExt};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let listener = TcpListener::bind("127.0.0.1:8080").await?;

    loop {
        let (socket, _) = listener.accept().await?;
        tokio::spawn(async move {
            handle_client(socket).await;
        });
    }
}

async fn handle_client(mut socket: TcpStream) {
    let mut buf = [0; 1024];

    loop {
        match socket.read(&mut buf).await {
            Ok(0) => break, // Connection closed
            Ok(n) => {
                if socket.write_all(&buf[0..n]).await.is_err() {
                    break;
                }
            }
            Err(_) => break,
        }
    }
}

Using timers and timeouts:

use tokio::time::{sleep, timeout, Duration};

#[tokio::main]
async fn main() {
    // Sleep for 1 second
    sleep(Duration::from_secs(1)).await;

    // Timeout an operation
    let result = timeout(Duration::from_secs(5), slow_operation()).await;

    match result {
        Ok(value) => println!("Operation completed: {:?}", value),
        Err(_) => println!("Operation timed out"),
    }
}

async fn slow_operation() -> &'static str {
    sleep(Duration::from_secs(10)).await;
    "done"
}

Spawning concurrent tasks:

use tokio::task;

#[tokio::main]
async fn main() {
    let handle1 = task::spawn(async {
        // Do some work
        println!("Task 1 completed");
        42
    });

    let handle2 = task::spawn(async {
        // Do some other work
        println!("Task 2 completed");
        "hello"
    });

    // Wait for both tasks to complete
    let (result1, result2) = tokio::join!(handle1, handle2);

    println!("Results: {:?}, {:?}", result1.unwrap(), result2.unwrap());
}

Modules§

fs
Asynchronous file utilities.
io
Traits, helpers, and type definitions for asynchronous I/O functionality.
net
TCP/UDP/Unix bindings for tokio.
process
An implementation of asynchronous process management for Tokio.
runtime
The Tokio runtime.
signal
Asynchronous signal handling for Tokio.
stream
Due to the Stream trait’s inclusion in std landing later than Tokio’s 1.0 release, most of the Tokio stream utilities have been moved into the tokio-stream crate.
sync
Synchronization primitives for use in asynchronous contexts.
task
Asynchronous green-threads.
time
Utilities for tracking time.

Macros§

join
Waits on multiple concurrent branches, returning when all branches complete.
pin
Pins a value on the stack.
select
Waits on multiple concurrent branches, returning when the first branch completes, cancelling the remaining branches.
task_local
Declares a new task-local key of type tokio::task::LocalKey.
try_join
Waits on multiple concurrent branches, returning when all branches complete with Ok(_) or on the first Err(_).

Functions§

spawn
Spawns a new asynchronous task, returning a JoinHandle for it.

Attribute Macros§

main
Marks async function to be executed by the selected runtime. This macro helps set up a Runtime without requiring the user to use Runtime or Builder directly.
test
Marks async function to be executed by runtime, suitable to test environment. This macro helps set up a Runtime without requiring the user to use Runtime or Builder directly.