Intel® oneAPI Threading Building Blocks
Ask questions and share information about adding parallelism to your applications when using this threading library.
2481 Discussions

How to do a parallel_reduce in TBB to append std::vector?

luca_l_
Beginner
1,695 Views

I've defined this reduction in OpenMP:

       std::vector<FindAffineShapeArgs> v;
    #pragma omp declare reduction(mergeFindAffineShapeArgs : std::vector<FindAffineShapeArgs> : omp_out.insert(omp_out.end(), omp_in.begin(), omp_in.end()))
    #pragma omp parallel for collapse(2) schedule(dynamic,1) reduction(mergeFindAffineShapeArgs : findAffineShapeArgs)
    for(int i=0; i<n; i++){
       v.push_back(//something);
    }

In few words, the reduction operation appends each local version of `v` to the global one.

I've never used TBB before, but I've read this, this and this tutorial, but I don't even understand if this is even possible in TBB.

Can someone help me with this please?

0 Kudos
1 Reply
Alexei_K_Intel
Employee
1,695 Views

Hi Luca,

Let me show the idea with lambda-based interface. The idea is similar to the OpenMP version: we need to specify the reduction loop with the first lambda and the reduction operation with the second lambda. With std::vector<int>() we specify the identity value (the value used to initialize each partial result).

std::vector<int> v = tbb::parallel_reduce(tbb::blocked_range<int>(0, n), std::vector<int>(),
        [](const tbb::blocked_range<int>& r, std::vector<int> v) -> std::vector<int> {
            for (int i = r.begin(); i != r.end(); ++i)
                v.push_back(i);
            return v;
        },
        [](std::vector<int> v1, std::vector<int> v2) -> std::vector<int> {
            v1.insert(v1.end(), v2.cbegin(), v2.cend());
            return v1;
        }
    );

Regards,
Alex

0 Kudos
Reply