#tokio #tokio-runtime #async-runtime #drop #async

tokio-async-drop

macro to enable async drop in a tokio multithreaded runtime

1 unstable release

0.1.0 Jul 2, 2023

#1878 in Asynchronous

Download history 231/week @ 2024-12-08 259/week @ 2024-12-15 9/week @ 2024-12-22 20/week @ 2024-12-29 119/week @ 2025-01-05 173/week @ 2025-01-12 213/week @ 2025-01-19 160/week @ 2025-01-26 113/week @ 2025-02-02 366/week @ 2025-02-09 795/week @ 2025-02-16 970/week @ 2025-02-23 750/week @ 2025-03-02 676/week @ 2025-03-09 432/week @ 2025-03-16 846/week @ 2025-03-23

2,731 downloads per month
Used in 6 crates

WTFPL license

5KB
63 lines

tokio-async-drop

This is a quick and dirty "hack" (not really an hack, since it's the desired behaviour of used components) to allow async drop in a tokio multithreaded runtime.

The same approach could potentially be used to allow async code in many other situations, e.g. inside a once_cell::sync::Lazy static variable.

Example

struct Foo<'a> {
    inner: &'a mut u8,
}

impl<'a> Foo<'a> {
    async fn bar(&mut self) {
        tokio::time::sleep(std::time::Duration::from_secs(1)).await;
        *self.inner = 1;
    }
}

impl<'a> Drop for Foo<'a> {
    fn drop(&mut self) {
        tokio_async_drop!({
            self.bar().await;
        });
    }
}

#[tokio::main]
async fn main() {
    let mut semaphore = 0;
    let f = Foo {
        inner: &mut semaphore,
    };
    drop(f);
    assert_eq!(semaphore, 1);
}

No runtime deps