3

I can iterate and process both index and the variable within such as:

let x = vec![5, 6, 7, 8];

for (index, val) in x.iter().enumerate() {
    println!("{} {}", val, index);
}

Now with rayon, from what I know, parallel iteration through par_iter() doesn't support enumerate because it has ParallelIterator.

Rayon seem to have IndexedParallelIterator, but I am not sure how to use it to produce similar result as the simple for loop shown above.

Is there anyway to keep track of the index of each value when parallel iterating? How would the simple for loop look like?

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98

1 Answers1

5

When you create a ParallelIterator from a Vec by calling par_iter() it's also simultaneously an IndexedParallelIterator so you can call enumerate() on it to get the item indexes like so:

// rayon = "1.5"
use rayon::prelude::*;

fn main() {
    let x = vec![5, 6, 7, 8];
    x.par_iter().enumerate().for_each(|(index, val)| {
        println!("{} {}", val, index);
    });
}

playground

vallentin
  • 23,478
  • 6
  • 59
  • 81
pretzelhammer
  • 13,874
  • 15
  • 47
  • 98