1.3 Reduction¶
The following program shows how to fix the integration example using the omp atomic pragma.
Take a look at the updated program below:
Another way to solve this issue is to employ the concept of reduction. The notion of a reduction comes from the mathematical operation
reduce, in which a collection of values are combined into a single value via a common mathematical function. Summing up a collection of
values is therefore a natural example of reduction. OpenMP provides the reduction clause for the omp parallel for pragma to show
that reduction should be used. The following example shows the integration example fixed using reduction clause:
The reduction clause (reduction(+: integral)) indicates that the addition operation should be used for reduction, and that that the final reduced value will be stored in the variable integral.
Note also that the integral variable was also removed from the shared clause.
1.3.1 Fix the array sum program¶
Now that you have learned what the reduction clause is, modify the array example to use reduction:
1.3.2 Summary¶
So far, we have introduced three different ways to deal with race conditions:
use the
omp criticalpragmause the
omp atomicpragmause a
reductionclause
OpenMP offers programmers multiple ways to deal with race conditions, because some techniques may be faster in different contexts. In the next section, we will discuss how to measure performance.