简体   繁体   English

openMP并行节中的共享变量有些奇怪

[英]Something strange with shared variable in openMP parallel sections

I got a strange phenomenon in openMP with shared monery and print function. 在具有共享monery和打印功能的openMP ,我遇到了一个奇怪的现象。

I tested this problem both in C++ and Fortran . 我在C++Fortran都测试了这个问题。

In C++: 在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: 在Fortan:

OpenMP performances a little different in Fortran. OpenMP在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. 但是,如果我评论线程1的打印,问题仍然存在。

I have to add sleep subroutine as the commented lines to get the expected result. 我必须添加sleep子例程作为注释行才能获得预期的结果。

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. 有关更多信息,请参见OpenMP 4.0标准的 1.4.1节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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