If you want to loop over the array items using rayon
then you can simply create into_par_iter
and work on array items
use std::process::Command;
use rayon::iter::{ParallelIterator, IntoParallelIterator};
fn main() {
let arr = [1, 2, 3, 4, 5];
let result: Vec<_> = arr.into_par_iter().flat_map(|value| {
let output = Command::new("sh")
.args(["-c", &format!("echo {}", value)])
.output()
.expect("failed to execute process");
println!("Index: {}, Output: {:?}", value, output.stdout);
output.stdout
});
println!("{:?}", result);
}
You can also use range
to loop over and use the counter
as array
index
use std::process::Command;
use rayon::iter::{ParallelIterator, IntoParallelIterator};
fn main() {
let arr = [1, 2, 3, 4, 5];
let result: Vec<_> = (0..arr.len()).into_par_iter().flat_map(|idx| {
let output = Command::new("sh")
.args(["-c", &format!("echo {}", arr[idx])])
.output()
.expect("failed to execute process");
println!("Index: {}, Output: {:?}", idx, output.stdout);
output.stdout
});
println!("{:?}", result);
}
Example using thread
use std::thread;
use std::time::Duration;
fn main() {
let mut threads = vec![];
for idx in 0..arr.len() {
threads.push(thread::spawn(move || -> Vec<_> {
let output = Command::new("sh")
.args(["-c", &format!("echo -n {}", idx)])
.output()
.expect("failed to execute process");
println!("Index: {}, Output: {:?}", idx, output.stdout);
thread::sleep(Duration::from_millis(1));
output.stdout
}));
}
let result = threads.into_iter().flat_map(|c| c.join().unwrap()).collect::<Vec<_>>();
println!("{:?}", result);
}