Skip to main content

Runtime

Trait Runtime 

Source
pub trait Runtime:
    Send
    + Sync
    + 'static {
    // Required methods
    fn spawn(
        &self,
        future: Pin<Box<dyn Future<Output = ()> + Send>>,
    ) -> AbortHandle;
    fn sleep(
        &self,
        duration: Duration,
    ) -> Pin<Box<dyn Future<Output = ()> + Send>>;
    fn spawn_blocking(
        &self,
        f: Box<dyn FnOnce() + Send>,
    ) -> Pin<Box<dyn Future<Output = ()> + Send>>;
    fn yield_now(&self) -> Option<Pin<Box<dyn Future<Output = ()> + Send>>>;

    // Provided method
    fn yield_frequency(&self) -> u32 { ... }
}
Expand description

A runtime-agnostic abstraction over async executor capabilities.

On native targets, futures must be Send (multi-threaded executors). On wasm32, Send is dropped (single-threaded).

Required Methods§

Source

fn spawn(&self, future: Pin<Box<dyn Future<Output = ()> + Send>>) -> AbortHandle

Source

fn sleep(&self, duration: Duration) -> Pin<Box<dyn Future<Output = ()> + Send>>

Source

fn spawn_blocking( &self, f: Box<dyn FnOnce() + Send>, ) -> Pin<Box<dyn Future<Output = ()> + Send>>

Source

fn yield_now(&self) -> Option<Pin<Box<dyn Future<Output = ()> + Send>>>

Cooperatively yield, allowing other tasks and I/O to make progress.

Use this in tight async loops that process many items to avoid starving other work. Returns None if yielding is unnecessary (e.g. multi-threaded runtimes where other tasks run on separate threads), or Some(future) that the caller must .await to actually yield.

Returning None avoids any allocation or async overhead, making the call zero-cost on runtimes that don’t need cooperative yielding.

Provided Methods§

Source

fn yield_frequency(&self) -> u32

How often to yield in tight loops (every N items). Defaults to 10. Single-threaded runtimes should return 1 to avoid starving the event loop.

Implementors§