Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ openMP并行部分中的共享变量有些奇怪_C++_Multithreading_Parallel Processing_Fortran_Openmp - Fatal编程技术网

C++ openMP并行部分中的共享变量有些奇怪

C++ openMP并行部分中的共享变量有些奇怪,c++,multithreading,parallel-processing,fortran,openmp,C++,Multithreading,Parallel Processing,Fortran,Openmp,我在openMP中发现了一个奇怪的现象,它具有共享货币和打印功能 我在C++和FORTRAN中测试了这个问题。 在C++中: 然而,我可以得到这样的结果: thread 1: 1 thread 2: -1726999 thread 2: -1727999 thread 2: -1728999 thread 2: -1729999 thread 2: -1730999 thread 2: -1731999 thread 2: -1732999 这是混乱的,看起来我没有分享!我试图评论这句话: p

我在openMP中发现了一个奇怪的现象,它具有共享货币和打印功能

我在C++和FORTRAN中测试了这个问题。 在C++中: 然而,我可以得到这样的结果:

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
现在看起来很好

福坦语: 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子例程作为注释行,以获得预期的结果

有人知道原因吗


另一个问题,在一个线程中修改变量的时间是否与在另一个线程中读取变量的时间相同?您正在修改多个线程中的共享变量,而无需同步。这就是所谓的数据竞赛。您的程序的结果未指定-任何事情都可能发生。如果在一个线程中写入变量,而在没有同步的情况下从另一个线程读取,则同样适用


有关更多信息,请参阅的第1.4.1节。

谢谢,在我的程序中,如果必须访问多线程中的变量,建议使用哪种方法?锁还是屏障?@在你的程序中,很难看到全局。。。存在多个线程只是为了更改同一个变量的值,这是不常见的。通常情况下,这正是避免的。
thread 2: 1
thread 2: -999
thread 2: 1
thread 2: 1
thread 2: -999
thread 2: 1
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