[英]Something strange with shared variable in openMP parallel sections
在具有共享monery和打印功能的openMP
,我遇到了一個奇怪的現象。
我在C++
和Fortran
都測試了這個問題。
#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
現在看起來不錯。
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.