Home > OS >  rust only 10 threads at a time
rust only 10 threads at a time

Time:07-12

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;
}

CodePudding user response:

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());
    });
}
  • Related