Tasks

Rust has a task system, which is a form of lightweight threading.

A task has a single top-level future which the executor polls to make progress. That future may have one or more nested futures that its poll method polls, corresponding loosely to a call stack. Concurrency within a task is possible by polling multiple child futures, such as racing a timer and an I/O operation.

  1. use tokio::io::{self, AsyncReadExt, AsyncWriteExt};
  2. use tokio::net::TcpListener;
  3. #[tokio::main]
  4. async fn main() -> io::Result<()> {
  5.     let listener = TcpListener::bind("127.0.0.1:0").await?;
  6.     println!("listening on port {}", listener.local_addr()?.port());
  7.     loop {
  8.         let (mut socket, addr) = listener.accept().await?;
  9.         println!("connection from {addr:?}");
  10.         tokio::spawn(async move {
  11.             socket.write_all(b"Who are you?\n").await.expect("socket error");
  12.             let mut buf = vec![0; 1024];
  13.             let name_size = socket.read(&mut buf).await.expect("socket error");
  14.             let name = std::str::from_utf8(&buf[..name_size]).unwrap().trim();
  15.             let reply = format!("Thanks for dialing in, {name}!\n");
  16.             socket.write_all(reply.as_bytes()).await.expect("socket error");
  17.         });
  18.     }
  19. }

This slide should take about 6 minutes.

Copy this example into your prepared src/main.rs and run it from there.

Try connecting to it with a TCP connection tool like nc or telnet.

  • Ask students to visualize what the state of the example server would be with a few connected clients. What tasks exist? What are their Futures?

  • This is the first time we’ve seen an async block. This is similar to a closure, but does not take any arguments. Its return value is a Future, similar to an async fn.

  • Refactor the async block into a function, and improve the error handling using ?.