ra1nsq
ra1nsq

Reputation: 11

Using tbb parallel for to iterate over std::map

I have two questions:

  1. I understand that I can use tbb::parallel(0, n, 1)[](i) {f(i)} to do a parallel for loop. What's the best way to parallel loop over a const std::map?

  2. If I want to append all outputs to a vector (ordering doesn't matter), how do I make this thread safe? i.e. I want to do something like:

    std::vector<A> output;
    tbb:parallel(0, n, 1)[&output](i) {
      std::vector<A> result = f(i);
      std::move(result.begin(), result.end(), std::back_inserter(output));
    }
    

Upvotes: 0

Views: 815

Answers (1)

Noorjahan - Intel
Noorjahan - Intel

Reputation: 99

  1. The Best way to parallelize a loop over a const std::map using Intel's TBB library is to use the tbb::parallel_for_each algorithm in combination with a TBB-compatible iterator.

    As elements in const std::map are not stored contiguously in memory, The tbb::parallel_for_each algorithm is designed to work efficiently with non-random access iterators, like the iterators used by std::map.

  2. To make your code thread-safe, you need to ensure that the access to the output vector is properly synchronized. One way to achieve this is to use a TBB concurrent container such as tbb::concurrent_vector instead of a regular std::vector.

    A concurrent_vector allows multiple threads to insert elements concurrently without explicit synchronization while maintaining the order of insertion.

Upvotes: 0

Related Questions