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)
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 thatlocal_maxis a member variable of the body class forparallel_reduce, and itsjoin()method receives another instance of the body and updateslocal_maxto be the bigger of the current value and the value in the other instance. Then after the call to parallel_reduce you take thelocal_maxvalue out of the original body object and assign it to the global variable.