Site Tools


reduction-openmp

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
reduction-openmp [June 11, 2026 at 11:06] – Ivan Janevskireduction-openmp [Unknown date] (current) – removed - external edit (Unknown date) 127.0.0.1
Line 1: Line 1:
-# Reduction (OpenMP) 
-Summing an array in serial C is a straightforward accumulation loop: 
- 
-```c 
-double sum = 0.0; 
-for (int i = 0; i < N; i++) 
-    sum += a[i]; 
-``` 
- 
-Adding `#pragma omp parallel for` to this loop creates a race condition: multiple threads read `sum`, add to it, and write back simultaneously, so some updates are lost. The `reduction` clause fixes this. 
- 
-**Reduction** in OpenMP gives each thread a private copy of the accumulation variable, lets it accumulate locally without contention, then merges all copies at the end of the loop using the specified operator. 
- 
-```c 
-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`. 
  
reduction-openmp.1781175977.md.gz · Last modified: by Ivan Janevski