#counter #raii #async

raii-counter-futures

RAII Counter that allows you to wait for a count of zero asynchronously

1 unstable release

0.1.0 Apr 15, 2020

#3 in #raii

Download history 140/week @ 2020-10-31 138/week @ 2020-11-07 71/week @ 2020-11-14 131/week @ 2020-11-21 88/week @ 2020-11-28 78/week @ 2020-12-05 136/week @ 2020-12-12 43/week @ 2020-12-19 6/week @ 2020-12-26 112/week @ 2021-01-02 265/week @ 2021-01-09 546/week @ 2021-01-16 515/week @ 2021-01-23 545/week @ 2021-01-30 370/week @ 2021-02-06 342/week @ 2021-02-13

395 downloads per month

MIT license

9KB
182 lines

raii-counter-futures

Fork of DarrenTsung's raii-counter library that allows you to wait asynchronously for the count to reach zero.

Demo

use raii_counter_futures::WeakCounter;
use std::time::Duration;

let weak = Arc::new(WeakCounter::new());
assert_eq!(counter.count(), 0);

let weak2 = Arc::clone(&weak);
tokio::spawn(async move {
    let counter1 = weak2.spawn_upgrade();
    let counter2 = weak2.spawn_upgrade();

    tokio::time::delay_for(Duration::from_secs(2)).await;
});

// Give the weak counters a chance to spawn, in a real workload you would not
// want to start waiting immediately after your async tasks spawn.
tokio::time::delay_for(Duration::from_millis(500)).await;

// This will not complete until the 2 second delay in the async task has finished.
counter.wait_for_empty().await;

lib.rs:

raii-counter

Rust type for a RAII Counter (counts number of held instances, decrements count on Drop), implemented with Arc<AtomicUsize>.

Useful for tracking the number of holders exist for a handle, tracking the number of transactions that are in-flight, etc.

Demo

use raii_counter_futures::Counter;

let counter = Counter::new();
assert_eq!(counter.count(), 1);

let weak = counter.downgrade();
assert_eq!(weak.count(), 0);

{
    let _counter1 = weak.spawn_upgrade();
    assert_eq!(weak.count(), 1);
    let _counter2 = weak.spawn_upgrade();
    assert_eq!(weak.count(), 2);
}

assert_eq!(weak.count(), 0);

Dependencies

~435KB