frederik
frederik

Reputation: 199

rust only 10 threads at a time

I want to run test(), but only 10 times at a time. Is there a way to create a max amount of threads and wait until one thread is complete before it starts a new one.

for (i, file) in files.iter().enumerate() {
     test(i, file).await;
}

Upvotes: 1

Views: 643

Answers (1)

trust_nickol
trust_nickol

Reputation: 2114

You can use rayon to process some data in parallel and limit the threads to be used for the processing.

Cargo.toml

[dependencies]
rayon = "1.5"

main.rs

use rayon::prelude::*;

fn test(i: usize, file: &str) {
    eprintln!("{:?}, {:?}", i , file);
}

fn main() {
    rayon::ThreadPoolBuilder::new().num_threads(10).build_global().unwrap();

    let mut files = vec![];
    for i in 0..100 {
        files.push(format!("tmp {}", i));
    }
    files.into_par_iter().enumerate().for_each(|(i, file)| {
      test(i, file.as_str());
    });
}

Upvotes: 2

Related Questions