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 methods
    fn spawn_detached(&self, future: Pin<Box<dyn Future<Output = ()> + Send>>) { ... }
    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 spawn_detached(&self, future: Pin<Box<dyn Future<Output = ()> + Send>>)

Spawn a task nobody will cancel.

Self::spawn has to hand back an AbortHandle, which boxes a dyn FnOnce capturing the executor’s own handle. Fire-and-forget callers pay for that box and drop it on the next line, so they get a path that never builds one. The default keeps the old behaviour for runtimes that do not override it.

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.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§

Source§

impl Runtime for InstrumentedRuntime

Source§

impl Runtime for TokioRuntime

Available on crate feature tokio-runtime and non-WebAssembly only.