Reduction
The reduction clause in OpenMP is used to perform a parallel reduction operation on a variable.
It helps avoid race conditions while performing aggregate operations like summation,
multiplication, finding minimum or maximum, etc., across threads.
How It Works:
1. Each thread has its own private copy of the variable.
2. The threads perform the operation independently on their local copies.
3. At the end of the parallel region, OpenMP combines the results from all threads using the
specified operator.
Syntax
operator: Specifies the reduction operation (e.g., +, *, max, min, &, |, etc.).
variable: The shared variable being reduced across threads.
#pragma omp parallel for reduction(operator : variable)
Operators:
Operator Operation Example
+ Addition Sum
* Multiplication Product
- Subtraction (since Difference
OpenMP 5.0)
max Maximum value Max of elements
min Minimum value Min of elements
& Bitwise AND Bitwise operations
` ` Bitwise OR
^ Bitwise XOR Bitwise operations
Activity 1: Summation
#include <iostream>
#include <omp.h>
int main() {
int sum = 0;
#pragma omp parallel for reduction(+ : sum)
for (int i = 0; i < 10; i++) {
sum += i;
}
std::cout << "Final sum: " << sum << '\n'; // Output: 45
return 0;
}
Activity 2: Finding Maximum Number
#include <iostream>
#include <omp.h>
int main() {
int sum = 0;
#pragma omp parallel for reduction(+ : sum)
for (int i = 0; i < 10; i++) {
sum += i;
}
std::cout << "Final sum: " << sum << '\n'; // Output: 45
return 0;
}
Activity 3: Sum of First 100 Natural Numbers Using reduction
#include <iostream>
#include <omp.h>
int main() {
int maxVal = INT_MIN;
int arr[] = {1, 4, 2, 9, 7, 5, 3, 8, 6, 0};
#pragma omp parallel for reduction(max : maxVal)
for (int i = 0; i < 10; i++) {
if (arr[i] > maxVal) {
maxVal = arr[i];
}
}
std::cout << "Maximum value: " << maxVal << '\n'; // Output: 9
return 0;
}