#tokio #asynchronous

tokio_safe_block_on

Provides the ability to execute async code from a sync context, without blocking a tokio core thread or busy looping the cpu

4 releases

0.2.0 Jun 24, 2020
0.1.2 Jun 5, 2020
0.1.1 Apr 22, 2020
0.1.0 Apr 21, 2020

#400 in Asynchronous

Download history 92/week @ 2020-11-01 131/week @ 2020-11-08 116/week @ 2020-11-15 13/week @ 2020-11-22 30/week @ 2020-11-29 46/week @ 2020-12-06 19/week @ 2020-12-13 11/week @ 2020-12-20 31/week @ 2020-12-27 67/week @ 2021-01-03 42/week @ 2021-01-10 32/week @ 2021-01-17 12/week @ 2021-01-24 20/week @ 2021-01-31 70/week @ 2021-02-07 43/week @ 2021-02-14

98 downloads per month

Apache-2.0

10KB
144 lines

Crates.io Crates.io

tokio_safe_block_on

Provides the ability to execute async code from a sync context, without blocking a tokio core thread or busy looping the cpu.

Example

#[tokio::main(threaded_scheduler)]
async fn main() {
    // we need to ensure we are in the context of a tokio task
    tokio::task::spawn(async move {
        // some library api may take a sync callback
        // but we want to be able to execute async code
        (|| {
            let r = tokio_safe_block_on::tokio_safe_block_on(
                // async code to poll synchronously
                async move {
                    // simulate some async work
                    tokio::time::delay_for(
                        std::time::Duration::from_millis(2)
                    ).await;

                    // return our result
                    "test"
                },

                // timeout to allow async execution
                std::time::Duration::from_millis(10),
            ).unwrap();

            // note we get the result inline with no `await`
            assert_eq!("test", r);
        })()
    })
    .await
    .unwrap();
}

Dependencies

~2.5MB
~43K SLoC