Hacker News new | past | comments | ask | show | jobs | submit login

The rust version of this has an inherent complexity that is very similar to your requirement. Processing at most X requests at once is the job of a Semaphore, until there's none left to process is the job of join_set.

    let mut tasks = JoinSet::new();
    let semaphore = Arc::new(Semaphore::new(12));
    for i in 0..100 {
        let semaphore = semaphore.clone();
        tasks.spawn(async move {
            let _permit = semaphore.acquire().await.unwrap();
            sleep(Duration::from_secs(1)).await;
            i * i // simulate some result
        });
    }
    
    while let Some(result) = tasks.join_next_with_id().await {
        let (id, result) = result?;
        println!("Task {id} result: {result}");
    }
That allows you to collect the results as they come in and align it to the various ids. If you only care about the final result and nothing why things are processing,

    let results = tasks.join_all();
The task is written inline there, but could as easily be an async function

    for i in 0..100 {
        tasks.spawn(process_request(i, semaphore.clone()));
    }





Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: