#single #run-time #sync #async #channel #testing #return

asyncified

A small library for operating on long lived sync values in an async context

9 releases (5 breaking)

0.6.2 Sep 12, 2023
0.6.1 Aug 30, 2023
0.5.0 May 6, 2023
0.4.0 May 1, 2023
0.1.0 Apr 29, 2023

#10 in #return

Download history 9/week @ 2024-06-10 14/week @ 2024-06-17 11/week @ 2024-06-24 26/week @ 2024-07-01 113/week @ 2024-07-08 58/week @ 2024-07-15 56/week @ 2024-07-22 91/week @ 2024-07-29 24/week @ 2024-08-05 141/week @ 2024-08-12 146/week @ 2024-08-19 171/week @ 2024-08-26 151/week @ 2024-09-02 61/week @ 2024-09-09 134/week @ 2024-09-16 76/week @ 2024-09-23

429 downloads per month
Used in 2 crates (via async-rusqlite)

MIT license

20KB
371 lines

Asyncified

A small, zero dependency, runtime agnostic Rust library for taking something that needs to operate in a single blocking thread and making it available to be operated on from an multiple tasks in an async context.

use asyncified::Asyncified;

// We can construct some blocking thing in a new thread:
let async_conn = Asyncified::new(|| database::connection());

// And then we can run blocking code which is handed a mutable reference
// to this thing, and await the result in a non-blocking way from our
// async context:
let res = async_conn.call(|db_conn| {
    let res = db_conn.execute("SELECT * FROM foo");
    res
}).await;

Calling Asyncified::new() spawns a new thread for the value to live in. That thread remains active until all of the Asyncified instance(s) are dropped. Using .call() dispatches functions to this new thread to be run in sequence in a blocking context.

The value passed to Asyncified::new() must be Send + 'static to be sent to this new thread, but does not need to be Sync, as it's only ever accessed on this one thread.

Warning: The channel implementations used to send functions and receive results from the sync thread are naive. In quick tests, the time taken to update a value and return it is in the order of a few microseconds, so it's good enough for my needs at the moment, since it's expected to be used with things like database connections which will dwarf this overhead.

No runtime deps