Combine Results with the OpenMP reduction Clause
Sum, count, min and max across threads without a data race using the OpenMP reduction clause, including initial values, array sections and float ordering.

Every parallel loop that produces one number, a sum, a maximum, a count of matches, runs into the same wall: all the threads want to write the same variable. A lock around the update works and removes the speedup. The reduction clause is the intended answer. Each thread accumulates into its own private copy, and when the loop ends the runtime combines the copies into the original variable. This post uses OpenMP 4.5 on GCC 14, shows the broken version and the fix, explains what the combiner and the initial value are, and covers the one place where reductions surprise people: floating-point addition is not associative. It builds on parallelizing a loop with a pragma, where the unsynchronized sum += i was the bug.
The broken sum and its fix
The data race first, so you can recognize it.
#include <stdio.h>
int main(void) {
long sum = 0;
#pragma omp parallel for
for (int i = 1; i <= 100000; i++) {
sum += i;
}
printf("sum = %ld\n", sum);
return 0;
}The sum of 1 through 100000 is 5000050000. This program gets that value only when the updates happen not to collide, and on a multicore machine they usually do.
sum = 3771208944The value differs on every run. Now the reduction.
#include <stdio.h>
int main(void) {
long sum = 0;
#pragma omp parallel for reduction(+:sum)
for (int i = 1; i <= 100000; i++) {
sum += i;
}
printf("sum = %ld\n", sum);
return 0;
}sum = 5000050000The loop body did not change. The clause reduction(+:sum) tells the compiler three things: sum is a reduction variable, the operator that combines partial results is +, and each thread needs a private sum initialized to the identity of +, which is zero. At the end of the loop the runtime adds every private copy into the original sum. The original value you assigned before the loop, here 0, is included in the combination, so starting sum at 100 would give 5000050100.
Operators and their starting values
The reduction operators in C are fixed by the specification, and each has a defined initial value for the private copies.
| Operator | Private copy starts at | Typical use |
|---|---|---|
+ | 0 | sums, counts |
- | 0 | treated like + for combining |
* | 1 | products |
& | ~0 (all bits set) | bitmask intersection |
| bitwise or | 0 | bitmask union |
^ | 0 | parity, checksums |
&& | 1 | "all of these are true" |
| logical or | 0 | "any of these are true" |
min | largest value of the type | smallest element |
max | smallest value of the type | largest element |
min and max were added to C and C++ reductions in OpenMP 3.1, so they are available on any current compiler. The initial values matter when you reason about an empty input: a max reduction over zero iterations returns the smallest representable value, not zero.
#include <stdio.h>
int main(void) {
int v[] = {42, 7, 19, 88, 3, 56, 71, 12};
int n = 8;
int lo = v[0];
int hi = v[0];
#pragma omp parallel for reduction(min:lo) reduction(max:hi)
for (int i = 0; i < n; i++) {
if (v[i] < lo) lo = v[i];
if (v[i] > hi) hi = v[i];
}
printf("min = %d, max = %d\n", lo, hi);
return 0;
}min = 3, max = 88You can list several reduction clauses on one construct, or several variables in one clause with reduction(+:a,b,c). Initializing lo and hi to v[0] is a habit worth keeping: because the original value takes part in the combination, a bad starting value corrupts the result. Starting lo at 0 here would return 0, not 3.
Counting matches
A count is a sum of ones, and the pattern appears constantly: how many records pass a filter.
#include <stdio.h>
int main(void) {
int temps[] = {18, 25, 31, 22, 35, 29, 40, 15, 33, 27};
int n = 10;
int hot = 0;
#pragma omp parallel for reduction(+:hot)
for (int i = 0; i < n; i++) {
if (temps[i] >= 30) hot++;
}
printf("days at or above 30: %d\n", hot);
return 0;
}days at or above 30: 4Integer reductions are exact and reproducible: the combination order does not change an integer sum. That is the property floating-point loses.
Floating-point reductions are not reproducible
Addition of real numbers is associative; addition of double values is not. A serial sum adds left to right. A parallel reduction adds each thread's chunk first and then combines the chunks, so the rounding errors land in a different order, and the final bits can differ.
#include <stdio.h>
int main(void) {
double x[] = {1e16, 1.0, -1e16, 1.0};
double sum = 0.0;
for (int i = 0; i < 4; i++) sum += x[i];
printf("left to right: %.1f\n", sum);
double a = x[0] + x[2];
double b = x[1] + x[3];
printf("paired: %.1f\n", a + b);
return 0;
}left to right: 1.0
paired: 2.0Both orders are legal, and the true mathematical answer is 2.0. The left-to-right sum loses the first 1.0 because 1e16 + 1.0 rounds back to 1e16. A parallel reduction picks a grouping you do not control, and which grouping it picks can change with the thread count. Two consequences follow. A test that compares a parallel double sum with the serial one needs a tolerance, not ==. And if you need bit-identical results across runs and thread counts, a reduction clause cannot promise it: the OpenMP specification does not fix the order of combining. You would need a fixed-shape tree, for example summing into an array with one slot per fixed-size block and adding the blocks in a serial loop afterward.
Reducing into an array
OpenMP 4.5 allows an array section as a reduction item, which handles histograms without a lock.
#include <stdio.h>
#define BINS 4
int main(void) {
int scores[] = {12, 47, 88, 63, 5, 91, 34, 72, 58, 20, 99, 41};
int n = 12;
int hist[BINS] = {0, 0, 0, 0};
#pragma omp parallel for reduction(+:hist[:BINS])
for (int i = 0; i < n; i++) {
int bin = scores[i] / 25;
if (bin > BINS - 1) bin = BINS - 1;
hist[bin]++;
}
for (int b = 0; b < BINS; b++) {
printf("bin %d: %d\n", b, hist[b]);
}
return 0;
}bin 0: 3
bin 1: 3
bin 2: 3
bin 3: 3The section hist[:BINS] means "start at the first element, length BINS". Each thread gets a private four-element array of zeros, and at the end the four slots are added slot by slot. This costs memory proportional to the thread count times the array length, so it suits a histogram with dozens of bins and not one with millions. For very wide arrays, per-thread arrays you merge yourself, or atomics, are the alternatives.
A custom reducer
For types and operations the built-in list does not cover, declare reduction (OpenMP 4.0) defines a combiner and an initializer.
#include <stdio.h>
typedef struct { double lo, hi; } Range;
static Range merge(Range a, Range b) {
Range r = { a.lo < b.lo ? a.lo : b.lo, a.hi > b.hi ? a.hi : b.hi };
return r;
}
#pragma omp declare reduction(rng : Range : omp_out = merge(omp_out, omp_in)) \
initializer(omp_priv = (Range){ 1e300, -1e300 })
int main(void) {
double v[] = {2.5, -1.0, 9.75, 4.0, 0.5, 7.25};
Range r = { 1e300, -1e300 };
#pragma omp parallel for reduction(rng:r)
for (int i = 0; i < 6; i++) {
Range one = { v[i], v[i] };
r = merge(r, one);
}
printf("range = [%.2f, %.2f]\n", r.lo, r.hi);
return 0;
}range = [-1.00, 9.75]omp_out is the accumulating value and omp_in is the incoming one. The initializer must produce the identity for your combiner, here an empty range. A combiner that is not associative gives different answers for different thread counts, the same trap as floating point.
What reductions cost and when to skip them
A reduction is cheap: one private variable per thread and one combine at the end. It does not cost a lock per iteration, which is why it beats #pragma omp critical on sum += x by a wide margin. Where it stops paying is the loop body. If the body is a single add and the array lives in main memory, the loop is limited by memory bandwidth, and extra threads add nothing. Measure before assuming scaling, and see profiling parallel scalability with perf for how.
Mistakes that survive a compile
Three errors with reductions compile cleanly and give wrong answers, so they are worth naming.
The first is updating the reduction variable somewhere other than the loop body, such as inside a critical section in the same loop. The variable inside the region is the private copy, and a critical block updating the original through another name, a pointer or a global, sidesteps the combining step and races with it. Update the reduction variable only through its own name, inside the construct that carries the clause.
The second is reading the result too early. The combined value exists only after the construct ends. When a reduction is on a for inside a larger parallel region and you add nowait, the final value is not guaranteed to be visible after the loop, only after the next barrier or the end of the region. Read it after the join.
#include <stdio.h>
int main(void) {
long total = 0;
#pragma omp parallel
{
#pragma omp for reduction(+:total)
for (int i = 1; i <= 100; i++) total += i;
#pragma omp single
printf("inside the region: %ld\n", total);
}
printf("after the region: %ld\n", total);
return 0;
}inside the region: 5050
after the region: 5050Here both reads are safe: the for has its implicit barrier, so the combined value is ready before the single reads it. Add nowait to the for and the first read becomes unsafe.
The third is using a reduction where the operation is not associative. A hand-written x = a[i] - x is not a reduction at all, and a compiler that accepts it gives each thread a partial result that makes no sense when combined. If you cannot write the operation as x = x op expr with an associative op, it is not a reduction.
For the authoritative option and behavior details, see the OpenMP specifications.


