:::info Rust 标准库 std::future::* 表示异步运行时的值 Asynchronous values :::

Structs

PollFn Experimental
A Future that wraps a function returning Poll.
Pending Creates a future which never resolves, representing a computation that never finishes.
Ready Creates a future that is immediately ready with a value.

Functions

poll_fn Experimental
Creates a future that wraps a function returning Poll.
pending Creates a future which never resolves, representing a computation that never finishes.
ready Creates a future that is immediately ready with a value.

RustStd.png

Traits

IntoFuture Experimental
Conversion into a Future.
Future A future represents an asynchronous computation.
  1. #[must_use = "futures do nothing unless you `.await` or poll them"]
  2. pub trait Future {
  3. type Output;
  4. fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
  5. }
  • Future: 一个future代表一个异步计算
  • Output: 关联类型Output代表异步计算得到的结果
  • poll: future的核心方法,任何情况下调用future都不会阻塞
    • 异步计算成功该方法会返回Poll::Ready(val)
    • 已经Ready过的任务再调用poll会panic
    • 异步计算未结束该方法返回Poll::Pending
    • 异步计算如果还没开始,那么会将其调度,然后返回Poll::Pending
    • poll方法是异步任务非阻塞、能完成的关键

说到这里,对于Future的全图还是不够清晰,我们知道这种poll触发推进异步任务更新状态的机制,但是也只是知道了这种抽象的方式:

  • poll如何实现?
  • Pin、Context真实的作用是如何发生的?
  • Waker如何在任务完成时wakeup() Future内部阻塞的异步计算任务?

以上问题仍待解决。