简体   繁体   中英

Something strange with shared variable in openMP parallel sections

I got a strange phenomenon in openMP with shared monery and print function.

I tested this problem both in C++ and Fortran .

In C++:

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h> 
int main (int argc, char *argv[]) 
{
int i=1;

#pragma omp parallel sections shared(i)
  {
    #pragma omp section
    {while(true){
        i = 1;
        printf("thread 1: %i\n", i);
    }}
    #pragma omp section
    {while(true){
        i = i - 1000;
        printf("thread 2: %i\n", i);
    }}
  }

}

This code is quite simple and the expected result is something like this:

thread 1: 1
thread 2: -999
thread 1: 1
thread 2: -999
thread 2: -1999
thread 1: 1

However, I could get this result:

thread 1: 1
thread 2: -1726999
thread 2: -1727999
thread 2: -1728999
thread 2: -1729999
thread 2: -1730999
thread 2: -1731999
thread 2: -1732999

It is confusing and looks like i is not shared! I tried to commented this line:

printf("thread 1: %i\n", i);

and got:

thread 2: 1
thread 2: -999
thread 2: 1
thread 2: 1
thread 2: -999
thread 2: 1

It looks fine now.

In Fortan:

OpenMP performances a little different in Fortran.

PROGRAM test
implicit none
integer*8 i
i = 1
 !$OMP parallel sections shared(i)
    !$OMP section
        do 
            i = 1 
            print *, "thread 1" ,i
            !call sleep(1)
        end do
    !$OMP section
        do 
            i = i-1000
            print *, "thread 2" ,i
            !call sleep(1)
        end do
 !$OMP end parallel sections
END PROGRAM

This code lead to the same problem as above. But if I comment the thread 1's print, the problem is still there.

I have to add sleep subroutine as the commented lines to get the expected result.

Anyone know the reason?

Another question, can a variable being modified in one thread as the same time as be reading in another thread?

You are modifying a shared variable from more than one thread without synchronization. This is known as a data race. The result of your program is unspecified - anything can happen. The same applies if you are writing to a variable in one thread and reading from another without synchronization.

See section 1.4.1 of the OpenMP 4.0 standard for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM