Futures
A Future is a value that may produce an output later. The executor calls poll; the future returns Pending or Ready(value). .await is syntax for that poll loop.
Detailed Explanation
trait Future { type Output; fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output>; } is the whole interface. Poll::Pending means "not yet; wake this task later via the Waker in cx". Poll::Ready(v) means done. An executor, such as Tokio, keeps a queue of tasks, polls them, and parks the thread when every task is pending.
You rarely implement Future by hand. async { } and async fn generate a state machine that implements it. You implement it when you are wrapping a file descriptor or writing a combinator. Then you must deal with Pin: the state machine can hold references to itself, so it must not move in memory after the first poll. Pin<&mut Self> is the type that says "this will not move".
Futures are lazy. Combining them (join!, select!, try_join!) still does nothing until the combined future is polled. join!(a, b) polls both and waits until both are ready. select! completes when the first of several is ready and cancels the others by dropping them.
A future is single-use. After Ready, polling again is a bug in most impls. They are not threads. They do not run in the background unless you tokio::spawn them, which puts them on the executor as a task.
When you name Future: trait bounds, boxed Pin<Box<dyn Future<Output = T> + Send>>, or combinators. When you write async: almost all application code. When you write poll by hand: drivers and libraries.
Combinators inherit cancellation. If select! completes the timeout arm, the I/O future is dropped at its current .await. A write that must be atomic with respect to the peer needs a design that does not drop mid-write, or a protocol that can resume. That is why people talk about cancellation safety: not every future is safe to drop at every await.
Code Examples
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
struct Ready(i32);
impl Future for Ready {
type Output = i32;
fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<i32> {
Poll::Ready(self.0)
}
}
#[tokio::main]
async fn main() {
println!("{}", Ready(7).await); // prints: 7
}Common Gotchas
A future does not run because it exists
Spawn it or await it. Dropping is cancel.
Self-referential futures must be pinned
The compiler inserts `Pin`. Moving a poll-in-progress future is UB. Do not `mem::swap` one out of a pinned slot.
`join!` waits for all, `select!` for the first
The loser of `select!` is dropped. That cancels its I/O.
`dyn Future` needs `Pin<Box<...>>`
Trait objects of futures are pinned boxes, not bare `Box<dyn Future>` in modern signatures.