#counter #future #async #shared #value #tasks #await

async_counter

Counter that implements a future to await on specific value

4 releases

0.1.3 May 17, 2024
0.1.2 May 15, 2024
0.1.1 May 15, 2024
0.1.0 Apr 18, 2024

#421 in Asynchronous

Download history 120/week @ 2024-06-11 113/week @ 2024-06-18 123/week @ 2024-06-25 148/week @ 2024-07-02 24/week @ 2024-07-09 37/week @ 2024-07-16 172/week @ 2024-07-23 114/week @ 2024-07-30 41/week @ 2024-08-06 134/week @ 2024-08-13 84/week @ 2024-08-20 116/week @ 2024-08-27 111/week @ 2024-09-03 39/week @ 2024-09-10 93/week @ 2024-09-17 159/week @ 2024-09-24

421 downloads per month

MIT/Apache

8KB
134 lines

This crate provides a counter that can be shared among different tasks and can be awaited until it reaches a specified value.

Consider the following scenario. Several asynchronous tasks are incrementing/decrementing a shared value. At the same time, another task needs to ensure that the shared value reaches at least a specific target. The following code demonstrates how to use the Counter in a simplified scenario. One child task increments the shared value, while the main task awaits it to reach a specific target.

let counter = Counter::to(10);
let mut count = counter.clone();

// Spawn a task to update the counter.
tokio::spawn(async move { 
    for i in 0u8..20 {
        // Simulate some processing
        time::sleep(Duration::from_secs(1)).await;
        count = count + 5;
        // or
        // count += 5;
    } 
});

// Wait for the target to be satisfied.
counter.await; 

No runtime deps