I want to add all the iterations that the loop went using the openmp reduction operator.
This is my code:
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#define CHUNKSIZE 2
#define N 100
int main (int argc, char *argv[])
{
int nthreads, tid, i, chunk;
float a[N], b[N], c[N];
/* Some initializations */
for (i=0; i < N; i++)
a[i] = b[i] = i * 1.0;
chunk = CHUNKSIZE;
int x=0;
#pragma omp parallel shared(a,b,c,nthreads,chunk) private(i,tid) reduction(+ : x)
{
tid = omp_get_thread_num();
if (tid == 0)
{
nthreads = omp_get_num_threads();
printf("Number of threads = %d\n", nthreads);
}
printf("Thread %d starting...\n",tid);
#pragma omp for schedule(static,chunk)
for (i=0; i<N; i++)
{
c[i] = a[i] + b[i];
printf("Thread %d: c[%d]= %f\n",tid,i,c[i]);
x++;
}
} /* end of parallel section */
printf("Value of x is %d" , x);
}
The problem is the final value of x is 100, not 200. I cannot understand the reason why I am not getting the expected value of 200. Could someone please help me?
100 is the expected outcome:
Each thread will get a set of two-element chunks from the
[0..N[interval, and only incrementxfor the values it got assigned. So the total number of timesx++will be executed, across all threads, isN.i.e. assuming three threads one will run the loop body for
i=0,1,6,7,12,13,..., the second thread fori=2,3,8,9,...and the third fori=4,5,10,11,....