Futures

Future 是一种 trait,由表示尚未完成的操作的对象所实现。可以轮询 Future,并且 poll 会返回 一个 Poll 对象。

#![allow(unused)]
fn main() {
use std::pin::Pin;
use std::task::Context;

pub trait Future {
    type Output;
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}

pub enum Poll<T> {
    Ready(T),
    Pending,
}
}

异步函数会返回 impl Future。对于自定义的类型,也可以实现 Future(但不常见)。例如,从 tokio::spawn 返回的 JoinHandle 会实现 Future,以允许加入该任务。

在 Future 中使用 .await 关键字会导致当前异步函数暂停,直到该 Future 准备就绪,然后计算其输出。

This slide should take about 4 minutes.
  • FuturePoll 类型的实现完全如下所示:请点击链接查看文档中的实现。

  • Context allows a Future to schedule itself to be polled again when an event such as a timeout occurs.

  • Pin ensures that the Future isn’t moved in memory, so that pointers into that future remain valid. This is required to allow references to remain valid after an .await. We will address Pin in the “Pitfalls” segment.