Site Tools


openmp-reduction

Table of Contents

OpenMP Reduction

Reduction in OpenMP gives each thread a private copy of an accumulation variable, lets it accumulate locally without contention, then merges all copies at the end of the loop using the specified operator. This fixes the race condition that occurs when naively adding #pragma omp parallel for to a serial loop like sum += a[i], where multiple threads would read, add, and write back simultaneously, losing updates:

double sum = 0.0;
 
#pragma omp parallel for reduction(+:sum)
for (int i = 0; i < N; i++) {
    sum += a[i];
}

Built-in reduction operators include +, *, -, min, max, and the bitwise operators &, |, ^. Custom reducers are possible in C++ via declare reduction.

openmp-reduction.md · Last modified: by 127.0.0.1