#thread #await #task #async #execute #tokio #duration

thread-async

Execute a task in a new thread and await the result asynchronously

1 unstable release

0.1.2 Sep 14, 2024
0.1.1 Sep 13, 2024
0.1.0 Sep 12, 2024

#1063 in Asynchronous

Download history 445/week @ 2024-09-11 50/week @ 2024-09-18 59/week @ 2024-09-25 36/week @ 2024-10-02

78 downloads per month
Used in scru64

CC0 license

12KB
151 lines

Crate thread_async

Crates.io License

Execute a task in a new thread and await the result asynchronously.

use std::{thread, time};

#[tokio::main]
async fn main() {
    let output = thread_async::run(|| {
        thread::sleep(time::Duration::from_millis(250));
        42
    })
    .await;

    assert_eq!(output, 42);
}

run() and its underlying primitive, run_with_builder(), execute the specified function in a separate thread and return a Future to .await the result. Each call to run() or run_with_builder() spawns a new thread that executes the specified function and wakes the current task upon completion. The specified function is triggered at the time of the call to run() or run_with_builder(), not at the time of .await.

This small crate is portable and works with any async executor, though it is suboptimal in performance as it creates a new thread for each task. Equivalent functions provided by async executors are usually recommended, unless a lightweight, executor-agnostic solution is specifically desired.

No runtime deps