Search code examples
ccygwinopenmp

C OpenMP code acts unexpectedly on cygwin but just as expected on Linux


int a = 0;
#pragma omp parallel private(a)
{
    a++;
    printf("%d", a);
}

With 4 cores one would expect this piece of code to print 1111, which it does on my Linux machine.

However, running the same piece of code (same flags etc) in cygwin on my Windows machine results in 11117 (not sure about the number of 1s).

The 7 is always there and a friend who tried the same also had the 7, Any ideas how this happens?

I compiled the code with "gcc source.c -fopenmp -O2" on both machines.


Solution

  • I did have difficulties to reproduce your error, since as I mentioned in my comment, your code has undefined behavior from an OpenMP standard point of view. Indeed, variables that are declared private upon entry of a parallel region do not get any initialization, unless they are declared firstprivate.

    In your case, you increment a variable which value can be whatever, and print it. So the printed value can be whatever as well, included the one you expected to see.

    I turns out that for me, in order to reproduce the series of 1s and a 7, I had to compile the code disabling any optimization from the compiler. And once the code was fixed with firstprivate, all results were 1s.

    Before fixing:

    $ gcc -O0 -fopenmp foo.c
    $ OMP_NUM_THREADS=5 ./a.exe
    71111
    $ OMP_NUM_THREADS=5 ./a.exe
    17111
    

    Code fixed:

    #include <stdio.h>
    int main () {
        int a = 0;
        #pragma omp parallel firstprivate(a)
        {
            a++;
            printf("%d", a);
        }
        return 0;
    }
    

    Then

    $ gcc -O0 -fopenmp foo.c
    $ OMP_NUM_THREADS=5 ./a.exe
    11111