thread-async

Crates.iothread-async
lib.rsthread-async
version0.1.2
sourcesrc
created_at2024-09-12 13:35:58.979948
updated_at2024-09-14 02:01:10.940729
descriptionExecute a task in a new thread and await the result asynchronously
homepage
repositoryhttps://github.com/LiosK/thread-async-rs
max_upload_size
id1372770
size18,319
LiosK (LiosK)

documentation

README

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.

Commit count: 0

cargo fmt