一、主要概念
1、Future
Futures 是异步计算产生的唯一最终值。不同的语言称呼不一,比如,javascript中称为“promise”.
源代码:
pub trait Future {
/// The type of value produced on completion.
#[stable(feature = "futures_api", since = "1.36.0")]
type Output;
#[stable(feature = "futures_api", since = "1.36.0")]
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}
2、Streams
Streams 描述为异步产生的一系列值。
pub trait Stream {
/// Values yielded by the stream.
type Item;
fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>>;
}
3、 Sinks
Sinks 为异步写数据提供支持。
pub trait Sink<Item> {
/// The type of value produced by the sink when an error occurs.
type SinkError;
fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::SinkError>>;
fn start_send(self: Pin<&mut Self>, item: Item)
-> Result<(), Self::SinkError>;
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::SinkError>>;
}
4、Executors
Executors负责运行异步的任务。
5、 task
轻量级的线程(a form of lightweight threading)。
大量的异步的计算是建立在futures,streams,sinks的基础之上;他们由独立运行并且要结束的任务产生,但是运行这些任务的线程并不会阻塞。
二、宏函数
1、join :
Polls multiple futures simultaneously, returning a tuple of all results once complete.
对多个futures同时进行轮询, 一旦有future完成,就返回相关结果。
2、pending
A macro which yields to the event loop once.
3、poll :轮询
A macro which returns the result of polling a future once within the current async context.
4、ready :
Extracts the successful type of a Poll.
5、select
Polls multiple futures and streams simultaneously, executing the branch for the future that finishes first. Futures passed to select! must be Unpin and implement FusedFuture. Futures and streams which are not already fused can be fused using the .fuse() method. Note, though, that fusing a future or stream directly in the call to select! will not be enough to prevent it from being polled after completion if the select! call is in a loop, so when select!ing in a loop, users should take care to fuse() outside of the loop.
6、try_join
Polls multiple futures simultaneously, resolving to a Result containing either a tuple of the successful outputs or an error.
7、try_ready
Extracts the successful type of a Poll<Result<T, E>>.