async-local-executor 0.4.0

Lightweight executor for building single-threaded async runtimes.
Documentation

async-local-executor   Action Badge Version Badge License Badge Docs Badge

Lightweight executor for building single-threaded async runtimes.

Why?

This crate provides an Executor for spawning and executing !Send futures without locks. It is meant to be integrated into an existing event loop and driven by that event loop whenever tasks need to make progress.

Usage

Examples of how to use the library can be found here. A short example of building a runtime on top of Executor is shown below.

use async_io::Timer;
use async_local_executor::{spawn_local, Executor, run_ready_tasks, exit};
use std::sync::mpsc;
use std::time::Duration;
use std::thread;

pub fn block_on<F>(future: F) -> F::Output
where
    F: IntoFuture + 'static,
{
    let thread = thread::current();
    let mut executor = Executor::new(move || thread.unpark());
    let _guard = executor.enter();
    let main = spawn_local(async move {
        let result = future.await;
        exit();
        result
    });
    loop {
        run_ready_tasks();
        if let Some(result) = main.result() {
            return result;
        }
        thread::park();
    }
}

fn main() {
    let res = block_on(async {
        spawn_local(async {
            for _ in 0..10 {
                println!("Hello, again!");
                Timer::after(Duration::from_secs(1)).await;
            }
        });
        for _ in 0..3 {
            println!("Hello, world!");
            Timer::after(Duration::from_secs(1)).await;
        }
        1
    });
    assert_eq!(res, 1);
}

This is basically the implementation of block_on

Contributing

If you find any errors in async-local-executor or just want to add a new feature feel free to submit a PR.