跳到主要内容

cooperative

搜索

函数 cooperative 

Source
pub fn cooperative<F: Future>(fut: F) -> Coop<F> 
展开描述

创建一个包装 future,使内部 future 与 Tokio 调度器协作。

轮询时, 包装器将首先调用 poll_proceed 以消耗任务 budget, 如果 budget 已耗尽则立即让出。 如果 budget 可用, 则轮询内部 future。 如果内部 future 解析为最终值, budget 消耗将通过 RestoreOnPending::made_progress 变为最终值。

§示例

tokio::sync::mpsc 通道的 Receiver 上调用 recv 时, 当返回下一个值时 任务 budget 将自动被消耗。 这使得使用 Tokio mpsc 通道的任务 自动成为协作式的。

如果你改用 futures::channel::mpsc, 则不会发生 自动的任务 budget 消耗。 本示例展示了如何使用 cooperativefutures::channel::mpsc 通道以与 Tokio 通道相同的方式 与调度器协作。

use tokio::task::coop::cooperative;
use futures::channel::mpsc::Receiver;
use futures::stream::StreamExt;

async fn receive_next<T>(receiver: &mut Receiver<T>) -> Option<T> {
    // Use `StreamExt::next` to obtain a `Future` that resolves to the next value
    let recv_future = receiver.next();
    // Wrap it a cooperative wrapper
    let coop_future = cooperative(recv_future);
    // And await
    coop_future.await
}