繁体   English   中英

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

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

在具有共享monery和打印功能的openMP ,我遇到了一个奇怪的现象。

我在C++Fortran都测试了这个问题。

在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);
    }}
  }

}

这段代码很简单,预期的结果是这样的:

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

但是,我可以得到以下结果:

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

这令人困惑,看起来我没有被分享! 我试图评论这一行:

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

并得到:

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

现在看起来不错。

在Fortan:

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

此代码导致与上述相同的问题。 但是,如果我评论线程1的打印,问题仍然存在。

我必须添加sleep子例程作为注释行才能获得预期的结果。

有人知道原因吗?

另一个问题,一个变量可以在另一个线程中同时读取一个变量吗?

您正在从多个线程修改共享变量而没有同步。 这称为数据竞赛。 程序的结果不确定-可能发生任何事情。 如果要在一个线程中写入变量并在不同步的情况下从另一个线程读取变量,则同样适用。

有关更多信息,请参见OpenMP 4.0标准的 1.4.1节。

暂无
暂无

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

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