pub fn poll_proceed(cx: &mut Context<'_>) -> Poll<RestoreOnPending>展开描述
减少 task 预算;若预算已耗尽,则返回 Poll::Pending。这表示 task 应让出(yield)给调度器。其他wise, returns
RestoreOnPending which can be used to commit the budget consumption.
返回的
RestoreOnPending
在丢弃时
会将 budget 恢复为其先前的值,
除非调用
RestoreOnPending::made_progress。
这是在调用
poll_proceed
之后能够取得进度时
由调用者负责完成的。
自动恢复 budget
可以确保任务能够
尝试通过其他方式取得进度。
请注意,
RestoreOnPending
将 budget 恢复为其在调用
poll_proceed
之前的状态。
因此,
如果在
poll_proceed
返回与
RestoreOnPending
丢弃之间
budget 被进一步调整,
则这些调整将被擦除,
除非调用者表明进度已经取得。
§示例
本示例包装
futures::channel::mpsc::UnboundedReceiver
以与 Tokio 调度器协作。
每次收到一个值时,
都会消耗任务 budget。
如果没有 budget 可用,
则任务会让出给调度器。
use std::pin::Pin;
use std::task::{ready, Context, Poll};
use tokio::task::coop;
use futures::stream::{Stream, StreamExt};
use futures::channel::mpsc::UnboundedReceiver;
struct CoopUnboundedReceiver<T> {
receiver: UnboundedReceiver<T>,
}
impl<T> Stream for CoopUnboundedReceiver<T> {
type Item = T;
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>
) -> Poll<Option<T>> {
let coop = ready!(coop::poll_proceed(cx));
match self.receiver.poll_next_unpin(cx) {
Poll::Ready(v) => {
// We received a value, so consume budget.
coop.made_progress();
Poll::Ready(v)
}
Poll::Pending => Poll::Pending,
}
}
}