4 releases

0.1.3 Jul 3, 2024
0.1.2 Jul 3, 2024
0.1.1 Mar 11, 2022
0.1.0 Mar 11, 2022

#550 in Asynchronous

Download history 48/week @ 2024-03-27 26/week @ 2024-04-03 2/week @ 2024-04-10 85/week @ 2024-04-17 66/week @ 2024-04-24 9/week @ 2024-05-01 7/week @ 2024-05-08 15/week @ 2024-05-15 12/week @ 2024-05-22 22/week @ 2024-05-29 13/week @ 2024-06-05 6/week @ 2024-06-12 3/week @ 2024-06-19 4/week @ 2024-06-26 230/week @ 2024-07-03 4/week @ 2024-07-10

241 downloads per month
Used in groupcache

MIT/Apache

15KB
302 lines

Singleflight Async

Crates.io MIT/Apache-2 licensed

Singleflight in async style.

Key Features

  • Execute an async task only once for the same key at the same time.
  • Cancel safe when the task is dropped.
  • Not requires the future to be Send/Sync, or 'static.
  • Works for all kind of runtimes including tokio, monoio, or others.

Example

use singleflight_async::SingleFlight;

#[tokio::main]
async fn main() {
    let group = SingleFlight::new();
    let mut futures = Vec::new();
    for _ in 0..10 {
        futures.push(group.work("key", || async {
            println!("will sleep to simulate async task");
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            println!("real task done");
            "my-result"
        }));
    }

    let begin = std::time::Instant::now();
    for fut in futures.into_iter() {
        assert_eq!(fut.await, "my-result");
        println!("task finished");
    }
    println!("time elapsed: {:?}", begin.elapsed());
}

The output will be like:

will sleep to simulate async task
real task done
task finished
task finished
task finished
task finished
task finished
task finished
task finished
task finished
task finished
task finished
time elapsed: 100.901321ms

Dependencies

~2.4–8.5MB
~58K SLoC