跳到主要内容

cooperative

搜索

函数 cooperative 

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

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

被 poll 时,wrapper 将首先调用 poll_proceed 来消耗任务预算,如果预算已用尽,则立即让步。如果预算可用,则 poll 内部 future。如果内部 future 解析为其最终值,则将使用 RestoreOnPending::made_progress 确定预算消耗。

§示例

当在 tokio::sync::mpsc channel 的 Receiver 上调用 recv 时,返回下一个值时会自动消耗任务预算。这使得使用 Tokio mpsc channel 的任务自动成为协作式的。

如果改用 futures::channel::mpsc,则不会自动消耗任务预算。此示例演示了如何使用 cooperative 使 futures::channel::mpsc channel 以与 Tokio channel 相同的方式与调度器协作。

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
}