Jakub M.
Jakub M.

Reputation: 33827

TBB: local and global results in parallel_for

I have a question regarding local values in a parallel loop, and updating a global variable.

Example, in pseudo-code: I am searching for a maximum value in a very long vector. I can do it in a loop, like that:

int max;
for(i ...) {
    if (max < vector[i]) max = vector[i];
}

I can easily parallelize it with OpenMP:

int max;
#pragma omp parallel
{
    int local_max;
#pragma omp parallel for
    for(i ...) {
        if (local_max < vector[i]) local_max = vector[i];
    }

#pragma omp critical
    {   
        // choose the best solution from all
        if (max < local_max) max = local_max; local_max
    }
}

How can I do the same in TBB parallel_for? I don't request an exact code, I would like just to know how to update the global result at the end of the loop, not at every iteration...

(I am new to TBB)

Upvotes: 1

Views: 849

Answers (1)

Alexey Kukanov
Alexey Kukanov

Reputation: 12784

What you do in this example is called reduction, so use parallel_reduce. It should be more efficient than updating a global variable under a lock. The basic idea is that local_max is a member variable of the body class for parallel_reduce, and its join() method receives another instance of the body and updates local_max to be the bigger of the current value and the value in the other instance. Then after the call to parallel_reduce you take the local_max value out of the original body object and assign it to the global variable.

Upvotes: 2

Related Questions