5 releases

0.2.0 Nov 6, 2024
0.1.3 Jul 3, 2024
0.1.2 Jul 3, 2024
0.1.1 Mar 11, 2022
0.1.0 Mar 11, 2022

#412 in Asynchronous

Download history 9/week @ 2024-08-12 19/week @ 2024-08-19 8/week @ 2024-08-26 5/week @ 2024-09-02 79/week @ 2024-09-09 25/week @ 2024-09-16 109/week @ 2024-09-23 52/week @ 2024-09-30 8/week @ 2024-10-07 362/week @ 2024-10-14 224/week @ 2024-10-21 186/week @ 2024-10-28 369/week @ 2024-11-04 426/week @ 2024-11-11

1,207 downloads per month
Used in groupcache

MIT/Apache

14KB
275 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