Youssef Khloufi
Youssef Khloufi

Reputation: 705

wrong results private array openmp

I am trying to write a code in C using openmp that runs on my dual core machine and that reads int values from an array and puts the results in an other array but i am getting wrong results. This is my code :

#include <stdlib.h>
#include <stdio.h>
#include <omp.h>

int array[10];
int array2[10];
int np,iam;

int main() {
  array[0]=12; // 0
  array[1]=21; // 21
  array[2]=13; // 26
  array[3]=31; // 93
  array[4]=40; // 160
  array[5]=32; // 160
  array[6]=16; // 96
  array[7]=51; // 357
  array[8]=7;  // 56
  array[9]=23; // 207

  int i;
  #pragma omp parallel for private(i,array)
  for(i=0;i<10;i++){
    #if defined (_OPENMP)
      np = omp_get_num_threads();
      iam = omp_get_thread_num();
    #endif
    printf("iam %d and i am doing % d\n",iam,i);
    array2[i] = array[i]*i;
  }

  for(i=0;i<10;i++){
    printf("%d ",array2[i]);
  }
  printf("\n");
  return EXIT_SUCCESS;
}

The non parallel version results are :

iam 0 and i am doing  0
iam 0 and i am doing  1
iam 0 and i am doing  2
iam 0 and i am doing  3
iam 0 and i am doing  4
iam 0 and i am doing  5
iam 0 and i am doing  6
iam 0 and i am doing  7
iam 0 and i am doing  8
iam 0 and i am doing  9
0 21 26 93 160 160 96 357 56 207

The parallel version results are :

iam 0 and i am doing  0
iam 0 and i am doing  1
iam 0 and i am doing  2
iam 0 and i am doing  3
iam 0 and i am doing  4
iam 1 and i am doing  5
iam 1 and i am doing  6
iam 1 and i am doing  7
iam 1 and i am doing  8
iam 1 and i am doing  9
0 -1217558997 1859518440 6 0 -1792801609 1284743096 -364 -1166026656 0 

Edit 1: I need the array "array" to be private. It have no sence in this case but i am trying to use an array as private to use it later in another case i am working on.

Upvotes: 0

Views: 668

Answers (1)

Youssef Khloufi
Youssef Khloufi

Reputation: 705

I found the solution to be using :

#pragma omp parallel for private(i) firstprivate(array)

firstprivate results in bringing in values from the outside context into the parallel region. Using private clause does not bring the values from the outside context, it just declare a private and not initialised variable so the variable has a random value.

Upvotes: 1

Related Questions