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:
Note
the keyword private
indicates that each thread will have its own copy of the variable i, whereas shared
is indicating that the variables a, n, h, and integral will be shared in memory by all of the threads.
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 the final reduced value will be stored in the variable integral
.
Note
The integral
variable is not included in the `shared
clause when moved to the reduction 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 critical
pragmause the
omp atomic
pragmause a
reduction
clause
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.