Intro to Asynchronous Programming
2026-11-10
This module: Asynchronous programming and company
Which of these might be most appropriate for a web browser to interact with a game server?
Respond at: https://PollEv.com/davidbindel252 or send davidbindel252 to 22333
Concurrency vs parallelism:
To share a core pre-emptively:
Three ways to exit running state
Spectrum based on style and workload:
Spectrum based on style and workload:
One thread per core
Several threads/core
Run-time scheduled tasks or handlers
select loops (event loops)
poll, epoll, kqueueWith some ambiguity in all cases:
Term from Java (designed by Green Team at Sun)
A coroutine is a subroutine that can be suspended
Many variations across languages!
A generator is a common type of coroutine
yield to return multiple outputsRust uses generators as an internal
JoinHandle in RustA Rust Future is between this and a coroutine
use tokio::time::{sleep, Duration};
async fn hello(id: usize, time: u64) {
println!("{id}: Hello, ... (and pause for {time} s)");
sleep(Duration::from_secs(time)).await;
println!("{id}: world!");
}
#[tokio::main]
async fn main() {
// All guaranteed to run on the same thread
tokio::join!(hello(0,2), hello(1,1), hello(2,1));
}async functions and blocks return a Futureawait awaits completion of an operation
async function or blockasync fn hello(...) is syntactic sugar for
where an async block compiles to a Future instance
cx used to access Waker (more on this Thursday)
What is the output?
Future doesn’t execute itself!h.await pauses current async function until result of h is readyawaitStream (cf async_stream crate)Future or Stream compiles to a state machineStart: Initial stateDone: Completed stateawait or yield(A little like the state machine for a process)
tokio, smolpoll futures#[tokio::main] lauches async main in executorpoll)epoll / kqueue / etc (maybe via mio)Adapted from https://rust-training.ferrous-systems.com/latest/slides/async-intro#/17
Which of these best describes a Rust task?
Respond at: https://PollEv.com/davidbindel252 or send davidbindel252 to 22333