首先:此问题在how can i keep variables private in subroutines which are called in a parallel section of openmp?和Are local variables in procedures automatically private when using OpenMP?等其他问题中得到了解决,但我的问题仍然如下。
我从OpenMP并行区域内部调用子例程,并希望局部变量对于每个线程都是私有的,因此在一个线程中对局部变量的更改不会影响其他线程。但是,我无法在此示例中使其工作:
program omp_private
use omp_lib
implicit none
call test() !initalize temp = 0
!$omp parallel
call test()
!$omp end parallel
contains
subroutine test()
integer :: temp = 0
if (omp_get_thread_num()==1) temp = 1
if (omp_get_thread_num()==0) write(*,*) "In thread ",omp_get_thread_num()," temp is ",temp
end subroutine test
end program omp_private
我的输出通常看起来像这样(取决于线程速度)
In thread 0 temp is 0
In thread 0 temp is 1
添加recursive
或save
改变了任何内容。我无法将temp
显式声明为私有,因为temp
未在子例程之外定义。
我怎么能让它发挥作用?