Fortran OpenMP中的全局变量 [英] Global Variables in Fortran OpenMP

查看:518
本文介绍了Fortran OpenMP中的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么只有将循环变量"i"和"j"作为子程序"mat_init"的输入参数,Fortran中的以下代码才起作用?循环变量"i"和"j"被声明为私有变量,所以当我调用它时,它们是否不应该在子例程中保持私有状态?

Why the following code in Fortran only works if I put the loop variables 'i' and 'j' as input arguments of the subroutine 'mat_init'? The loop variables 'i' and 'j' are declared as private, so shouldn't they remain private inside the subroutine when I call it?

program main
   use omp_lib
   implicit none
   real(8), dimension(:,:), allocatable:: A
   integer:: i, j, n

   n = 20
   allocate(A(n,n)); A(:,:) = 0.0d+00

   !$omp parallel do private(i, j)
   do i=1,n
   do j=1,n
   call mat_init
   end do
   end do

   do i=1,n
   write(*,'(20f7.4)') (A(i,j), j=1,n)
   end do

contains
   subroutine mat_init

      A(i,j) = 1.0d+00
   end subroutine
end program main

我知道这与'lexical'和'dynamic'扩展有关,但是我不明白为什么OpenMP是用这种方式实现的,以便不能在并行中识别'dymanic'扩展中的私有变量地区.对我来说,这似乎不合逻辑,或者我做错了什么?

I know this have something to do with the 'lexical' and 'dynamic' extend, but I don't understand why OpenMP is implemented in this way to don't recognize private variables in the 'dymanic' extend inside de parallel regions. For me it seems not to be logical or am I doing anything wrong?

推荐答案

首先,我认为子例程mat_init应该明确将i和j的值作为输入参数.然后,i和j的值必须是私有的,因为每个线程都对i和j的特定值起作用.我还认为openmp会认识到我是私有的,因为并行化循环位于i上.同上j.但是,这适用于全局变量i和j,而不适用于子例程内部的那些变量.因此,您必须指定i和j为私有,以强制子例程内部变量体现这一方面.

First, I think that the subroutine mat_init should takes the value of i and j as input arguments explicitly. Then, the value of i and j must be private, because each thread works on a specific value of i and j. I think also that openmp recognizes that i is private because the parallelized loop is on i. Idem for j. However, this work for the global variables i and j and not for those ones who are internal to the subroutine. Thus, you have to specify that i and j are private in order to force the subroutine internal variables to inhiritate of this aspect.

我认为问题是由于子例程mat_init的重新进入.确实,当多个线程同时以不同的i和j值进入子例程时,会发生什么?如果您不执行任何特殊操作,则被调用的子例程可能无法识别i和j的私有方面.

I believe that the problem is due to the reentrance of the subroutine mat_init. Indeed, what happen when multiple threads enter the subroutine at the same time with different value of i and j? If you don't do any special thing, the called subroutine might not recognize the private aspect of i and j.

通常,不欢迎在循环内多次调用子例程,因为每次调用都需要一定的时间.我建议编写一个并行化的子例程,而不是在并行化的部分中调用该子例程.

In general, it is not welcomed to call many times a subroutine inside a loop, because each call requires a given time. I suggest to write a subroutine that is parallelized rather than call a subroutine within a parallelized section.

这篇关于Fortran OpenMP中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆