简体   繁体   中英

Rust + Tokio: Process First Task to Complete

In Tokio, how do you wait for the first task in a list of tasks to complete? The size of the list is unknown.

More specifically:

  1. You have a list of tasks.
  2. Wait for the first that completes.
  3. Run some code, including possibly adding more tasks to the list.
  4. Repeat until the list is empty.

The context is that I'm trying to write a function that will run at most N tasks at a time.

If using tokio , the general template is this:

use futures::stream::FuturesUnordered;
use tokio::task::JoinHandle;

let futs = data
    .into_iter()
    .map(|datum| {
        tokio::spawn(async move {
            compute_value(datum)
        })
    })
    // The _ is inferred to be the return type of `compute_value`
    .collect::<FuturesUnordered<JoinHandle<_>>>();

while let Some(result) = futs.next().await {
    let value = result?;  // a potential stream error
    // use value
}
 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM