Home > Net >  Duplicate threads showing up when they should be unique (OpenMP)
Duplicate threads showing up when they should be unique (OpenMP)

Time:11-22

I have to write a code that calculates a partial sum : S(i) = Σ a(j) (j going from 0 to i). Each time, i have to show the value of S(i) (named somme in the code) in the loop, and I have to code it with OpenMP. This is my code :

#include <stdio.h>
#include <omp.h>
#define n 16

int main(void) {
    int a[n] = {2,3,6,9,4,7,0,2,2,6,8,9,11,0,2,4};
    int i, j, t, somme;

    #pragma omp parallel num_threads(16)
    #pragma omp for
    for (i=0; i<n; i  ){
        t = omp_get_thread_num();
        somme = a[0];
        for (j=1; j<i 1; j  ) somme  = a[j];
        printf("<%d>: S(%d) = %d\n", t, i, somme);
    }
    return 0;
}

However, when I run the code with 16 threads, some threads are duplicated, and the result of those threads is wrong :

  <15>: S(15) = 75
  <7>: S(7) = 33
  <6>: S(2) = 11
  <6>: S(6) = 31
  <8>: S(8) = 35
  <9>: S(9) = 41
  <10>: S(10) = 49
  <11>: S(11) = 58
  <14>: S(14) = 71
  <12>: S(12) = 69
  <14>: S(13) = 69
  <5>: S(5) = 35
  <3>: S(3) = 20
  <0>: S(0) = 2
  <5>: S(1) = 35
  <4>: S(4) = 24

I have asked my professor, and he has no clue what is going on. I don't understand why my code is behaving like this, can anyone help me?

CodePudding user response:

As mentioned by @EOF you have data races due to shared variables (i,j,t,somme). You have to make them private:

#pragma omp for private(i,j,t,somme)

or even better if you define your variables in their minimum required scope:

int main(void) {
    int a[n] = {2,3,6,9,4,7,0,2,2,6,8,9,11,0,2,4};

    #pragma omp parallel num_threads(16)
    #pragma omp for
    for (int i=0; i<n; i  ){
        int t = omp_get_thread_num();
        int somme = a[0];
        for (int j=1; j<i 1; j  ) somme  = a[j];
        printf("<%d>: S(%d) = %d\n", t, i, somme);
    }
    return 0;
}
  • Related