Sha256: 7884eb4b7c53769d0560ddeea1801449814002740676d72a4671916239b2936a

Contents?: true

Size: 1.26 KB

Versions: 5

Compression:

Stored size: 1.26 KB

Contents

use std::task::{ready, Poll};

/// Consumes a unit of budget and returns the execution back to the Tokio
/// runtime *if* the task's coop budget was exhausted.
///
/// The task will only yield if its entire coop budget has been exhausted.
/// This function can be used in order to insert optional yield points into long
/// computations that do not use Tokio resources like sockets or semaphores,
/// without redundantly yielding to the runtime each time.
///
/// # Examples
///
/// Make sure that a function which returns a sum of (potentially lots of)
/// iterated values is cooperative.
///
/// ```
/// async fn sum_iterator(input: &mut impl std::iter::Iterator<Item=i64>) -> i64 {
///     let mut sum: i64 = 0;
///     while let Some(i) = input.next() {
///         sum += i;
///         tokio::task::consume_budget().await
///     }
///     sum
/// }
/// ```
#[cfg_attr(docsrs, doc(cfg(feature = "rt")))]
pub async fn consume_budget() {
    let mut status = Poll::Pending;

    std::future::poll_fn(move |cx| {
        ready!(crate::trace::trace_leaf(cx));
        if status.is_ready() {
            return status;
        }
        status = crate::runtime::coop::poll_proceed(cx).map(|restore| {
            restore.made_progress();
        });
        status
    })
    .await
}

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
wasmtime-30.0.2 ./ext/cargo-vendor/tokio-1.43.0/src/task/consume_budget.rs
wasmtime-29.0.0 ./ext/cargo-vendor/tokio-1.43.0/src/task/consume_budget.rs
wasmtime-28.0.0 ./ext/cargo-vendor/tokio-1.43.0/src/task/consume_budget.rs
wasmtime-27.0.0 ./ext/cargo-vendor/tokio-1.41.1/src/task/consume_budget.rs
wasmtime-26.0.0 ./ext/cargo-vendor/tokio-1.41.0/src/task/consume_budget.rs