一、主要概念
1、Future
Futures 是异步计算产生的唯一最终值。不同的语言称呼不一,比如,javascript中称为“promise”.
源代码:
1
2
3
4
5
6
7
8
9 1pub trait Future {
2 /// The type of value produced on completion.
3 #[stable(feature = "futures_api", since = "1.36.0")]
4 type Output;
5 #[stable(feature = "futures_api", since = "1.36.0")]
6 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
7}
8
9
2、Streams
Streams 描述为异步产生的一系列值。
1
2
3
4
5
6
7
8
9
10 1pub trait Stream {
2 /// Values yielded by the stream.
3 type Item;
4 fn poll_next(
5 self: Pin<&mut Self>,
6 cx: &mut Context<'_>,
7 ) -> Poll<Option<Self::Item>>;
8}
9
10
3、 Sinks
Sinks 为异步写数据提供支持。
1
2
3
4
5
6
7
8
9
10 1 pub trait Sink<Item> {
2 /// The type of value produced by the sink when an error occurs.
3 type SinkError;
4 fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::SinkError>>;
5 fn start_send(self: Pin<&mut Self>, item: Item)
6 -> Result<(), Self::SinkError>;
7 fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::SinkError>>;
8}
9
10
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>>.