我想对用户定义的Fortran类型进行OpenMP缩减。我知道OpenMP在归约子句中不支持Fortran类型,但可以定义自己减少。在以下示例中完成此操作。这也起作用并且做它是什么预期
module types
!!! your type this can contain scalars and arrays
type my_type
Real*8,allocatable,dimension( : ) ::x
end type
!!! makes it possible to use the plus symbol for the reduction staement
!!! replaces my_add by plus symbol
interface operator(+)
module procedure :: my_add
end interface
!$omp declare reduction (+ : my_type : omp_out = omp_out + omp_in) initializer (omp_priv = my_type ([0,0,0,0,0,0,0,0,0,0]))
contains
function my_add( a1 , a2 )
type( my_type ),intent( in ) :: a1, a2
type( my_type ) :: my_add
my_add%x = a1%x + a2%x
return
end function my_add
end module types
program main
use types
use omp_lib
type(my_type) :: my_var
! Initialize the reduction variable before entering the OpenMP region
Allocate( my_var%x( 1:10 ) )
my_var%x = 0d0
!$omp parallel reduction (+ : my_var) num_threads(4)
my_var%x = omp_get_thread_num() + 6
print*,omp_get_thread_num()
!$omp end parallel
print *, "sum of x is ", my_var%x
end program
我的问题现在是可分配的数组。
因为我将OpenMP减少语句的数组初始化程序硬编码为initializer (omp_priv = my_type ([0,0,0,0,0,0,0,0,0,0]))
由于数组分配的长度为10,因此我必须在其中放置10个零。可以使用变量名N(数组长度)吗?
在简化初始值设定项中,我们对变量的访问受到限制,这使得可变长度的数组构造函数很困难。但是,我们可以使用C++ approach的Fortran版本。
我们可以使用变量omp_orig
来指代“要减少的原始变量的存储”:
!$omp declare reduction (+ : my_type : omp_out = omp_out + omp_in) &
!$omp& initializer (omp_priv=omp_orig)
这里的赋值语句成功分配了每个私有副本的数组组件。