0

Consider the following:

// compile with
// gcc -fopenmp test.c

#include <stdio.h>    // to display on the screen
#include <stdlib.h>   // to access EXIT_SUCCESS
#include <omp.h>      // OpenMP library.

int main() {
  unsigned long long input = 100;
  unsigned long long b = 0, c = 0;
  #pragma omp parallel
  {
    #pragma omp for
    for(unsigned long long a = 0 ;  a < input ; a++) {
      b++;
      c++;
    }
  } // <= There should be a barrier here.
  // Check
  if (b != c || b != input){
      fprintf(stdout, "\"Error\" : %llu and %llu are different from %llu", b, c, input);
      return EXIT_FAILURE;
  }
  else{
    return EXIT_SUCCESS;
  }
}

My current understanding is that there should be an implicit barrier at the end of the #pragma omp parallel { block, so that all threads should have completed when the code reach the if statement.

However, I get inconsistent results:

gcc -fopenmp test.c
./a.out 
"Error" : 70 and 69 are different from 100
./a.out 
"Error" : 75 and 78 are different from 100
./a.out 
"Error" : 83 and 81 are different from 100
./a.out 
"Error" : 91 and 86 are different from 100
./a.out  <= Nothing, which means it "worked"
./a.out 
"Error" : 88 and 86 are different from 100

What is flawed in my understanding?

Clément
  • 2,358
  • 28
  • 32
  • 1
    Why do you think operations such as `b++` are atomic? – Andrew Henle Mar 19 '22 at 15:47
  • There is a race condition on `b` and `c` since the values are *shared* amongst threads. And yes there is a barrier at the end of the parallel section but the problem is the race condition. – Jérôme Richard Mar 19 '22 at 15:51
  • Ok, so the iterations are shared, but since every threads increment `b` and `c`, there is a race condition. Is there any way to correctly optimize / parallelize such a loop with openmp? – Clément Mar 19 '22 at 15:59
  • 3
    You can use `#pragma omp atomic` before `b++` and `c++` or you can use reduction. My suggestion is to read a decent book about OpenMP or at least read [this](https://stackoverflow.com/questions/26998183/how-do-i-deal-with-a-data-race-in-openmp). – Laci Mar 19 '22 at 16:33

0 Answers0