Search code examples
c++openmpshared-memorysharedreduction

Reduction(op:var) has the same effect as shared(var)


I've tried this code snippet for reduction(op:var) proof of concept, it worked fine and gave a result = 656700

int i, n, chunk;
float a[100], b[100], result;
/* Some initializations */
n = 100; chunk = 10; result = 0.0;
for (i=0; i < n; i++) {
    a[i] = i * 1.0;
    b[i] = i * 2.0;
}
//Fork has only for loop
#pragma omp parallel for default(shared) private(i) schedule(static,chunk) reduction(+:result)
for (i=0; i < n; i++)
    result = result + (a[i] * b[i]);
printf("Final result= %f\n",result);

When i tried the same code but without reduction(+:result) it gave me the same result 656700 ! I think this makes very sense as reduction rely on a shared variable, in another words, shared clause would be sufficient for such operation.

I am confused!


Solution

  • Reduction uses a shared variable visible to you, but private copies of the variable internally. When you forget the reduction clause more threads may try to update the value of the reduction variable at the same time. That is a race condition. The result may likely be wrong and it will also will slow, because of the competition for the same resource.

    With reduction, every thread has a private copy of the variable and works with it. When the reduction region finishes, the private copies are reduced using the reduction operator to the final shared variable.