I'm studying for an exam at the moment and one of the practice questions is to write a piece of code which implements the parallel sum of all element of an array on an SMP computer. I've written a few OpenMP programs before which were much large but didn't take advantage really of the clauses and directives and I came across the reduction clause so I was wondering if the following piece is a parallel program because I'm wondering how relatively simplistic could one reduce the program to but still retain parallelisation?
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
int main(int argc, char ** argv){
int n = atoi(argv[1]);
double * X;
X = malloc(n * sizeof(double));
for(int i = 0; i < n; i++){ X[i] = 2.0; }
int i = 0;
double sum = 0.0;
omp_set_num_threads(atoi(argv[2]));
#pragma omp parallel for private(i), shared(X) reduction(+: sum)
for(i = 0; i < n; i++){
sum += X[i];
}
printf("Sum is : %0.2f\n", sum);
return 0;
}
I came across the reduction clause so I was wondering if the following piece is a parallel program
From the OpenMP standard on the #pragma omp parallel
:
When a thread encounters a parallel construct, a team of threads is created to execute the parallel region. The thread that encountered the parallel construct becomes the master thread of the new team, with a thread number of zero for the duration of the new parallel region. All threads in the new team, including the master thread, execute the region. Once the team is created, the number of threads in the team remains constant for the duration of that parallel region.
So yes, it is a parallel program as long as the number of threads that you have explicitly set it on the method:
omp_set_num_threads(atoi(argv[2]));
is greater than 1.
In:
#pragma omp parallel for private(i), shared(X) reduction(+: sum)
The private i
can be omitted, because since it is used as the index
on the parallel loop, OpenMP will make it private.