Poll-based cooperative multitasking, zero-cost state machines, Wakers, and Tokio multi-threaded work-stealing reactor.
use tokio::time::{sleep, Duration};
async fn fetch_metrics(service_id: u32) -> String {
sleep(Duration::from_millis(50)).await; // Non-blocking yield
format!("Service {} latency: 4ms", service_id)
}
#[tokio::main]
async fn main() {
let task1 = tokio::spawn(fetch_metrics(1));
let task2 = tokio::spawn(fetch_metrics(2));
let (res1, res2) = tokio::join!(task1, task2);
println!("Results: {:?}, {:?}", res1.unwrap(), res2.unwrap());
}Unlike Go goroutines or Node.js event loops, Async Rust futures do not allocate a separate stack or run automatically in the background.
The `Future` trait defines a single required method: `fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>`.
When a future returns `Poll::Pending`, it registers the current task's `Waker` with the event source. When the data arrives (e.g. packet on socket), the kernel signals Tokio via `epoll`, which wakes the task and puts it back onto the worker queue.
The compiler translates each `.await` point into a distinct variant of an anonymous enum, capturing only the live variables that span across that suspension point.
// Conceptual transformation:
enum FetchMetricsState {
Start,
WaitingOnSleep(tokio::time::Sleep),
Done,
}