Rust’s Future is the core abstraction for async programming. What follows is how async/await, polling, and the runtime stack fit together.
async gives you cheap, suspendable functions; they only run when you .await them and the executor polls them.
Compared with one OS thread per bit of concurrency, async tasks are lighter—you can host many concurrent operations without paying for a thread each time.
A minimal async entry point:
1 | async fn async_fn() { |
State machine
async is mostly compiler sugar: it implements Future for you and stores progress in a state machine.
1 | trait Future { |
poll asks whether the work is done. A task is either Pending (yield control until something can make progress) or Ready (finished). The executor keeps polling until Ready.
We can see that flow by implementing a small Delay future:
1 | use std::future::Future; |
Each poll checks the deadline. If time has passed, return Ready; otherwise schedule another wake and return Pending.
We have a state machine—who drives it?
Scheduling
Rust needs a runtime to schedule async tasks. The runtime polls futures and advances work.
When a future returns Pending, the task yields and arranges to be woken later.
Typical path when work completes on the first poll:
graph TD
executor --> task
task -- poll --> future
future -- ready --> task
When the future is Pending, something must schedule the next wake. The wake may run on a different task than the one that polled last time. The waker travels through Context on every poll:
graph TD
executor --> task
executor --> waker
executor -.-> task
task -- poll with context (waker) --> future
future -- update --> waker
future -- pending --> task
waker -- wake --> executor
Runtime
Scheduling lives in a runtime. Rust’s standard library does not ship one; most projects use Tokio.
#[tokio::main] expands to a multi-thread runtime that blocks until the async main finishes:
1 |
|
Single-thread flavor:
1 |
|
async
You rarely implement Future by hand. async fn is enough—the Delay example collapses to something like this:
1 | use std::sync::Arc; |
pin
Remember Pin<&mut Self> on poll—why pin a future?
1 | async fn my_async_fn() { |
Polling through a stack reference fails unless the future is Unpin.
A Future from async is a state machine that moves while polled. If it held stack references, those addresses would go stale when the state machine moves—classic use-after-move.
Unpin marks types that are safe to move while referenced. Most ordinary types are Unpin. For !Unpin futures, pin them on the stack (pin!) or heap (Box::pin) so the address stays valid until completion:
1 | use tokio::pin; |
That’s enough for one sitting. Next up: running several futures concurrently.
More on pinning: Pinning
Tokio’s runtime tour: Async in depth
Questions? Leave a comment below or email: newbvirgil@gmail.com![]()
