用fopenmp编译的Fortran程序只显示一个线程

时间:2015-05-05 11:35:35

标签: multithreading fortran openmp fortran90 gfortran

我在Fortran中有一个很大的代码,它有一个商业许可证,所以我不能 发布代码。它包含几个模块,每个模块都有几个子程序。我使用-fopenmp标志编译了该代码(我使用了标志 对于程序中的所有文件)。

在一个子程序中,我放置了代码

!$OMP PARALLEL
       nthreads=OMP_GET_NUM_THREADS()
       write(6,*) 'threads', nthreads
!$OMP END PARALLEL

最初,该程序抱怨无法识别的OMP_GET_NUM_THREADS数据类型。我在这个论坛上看到了一些帖子 使用use omp_lib加载运行时库是suggested。后 将这一行添加到子程序中,程序运行但是打印了

  

线程1

好像只有一个线程被使用,即使我设置

export OMP_NUM_THREADS=10

我的问题是,我应该在每个子程序中使用use omp_lib吗?或者可能 只在“主要”节目?

正如我之前所说,这个子程序(我编写omp指令的地方)是 在一个模块内。

1 个答案:

答案 0 :(得分:0)

您需要在子例程的范围内声明OMP_Get_num_threads()。这可能发生在该子例程中的use语句中,或者,因为您在模块的标题中使用模块。在下面粘贴的片段中,我做了两个。

注意,对OMP_Get_num_threads()的函数调用需要嵌入到并行部分中(就像在代码片段中所做的那样),否则结果总是1

由于模块无法访问主程序的范围,因此use模块不够用(但编译器会在链接二进制文件时告诉您)。

module testMod
  use omp_lib, only: OMP_Get_num_threads
  implicit none

contains

  subroutine printThreads()
    use omp_lib, only: OMP_Get_num_threads
    implicit none

    ! This will always print "1"
    print *,OMP_Get_num_threads()

    ! This will print the actual number of threads
    !$omp parallel
    print *,OMP_Get_num_threads()
    !$omp end parallel
  end subroutine

end module

program test
  use testMod, only: printThreads
  implicit none

  call printThreads()
end program

具有以下结果:

OMP_NUM_THREADS=2 ./a.out 
           1
           2
           2

OMP_NUM_THREADS=4 ./a.out 
           1
           4
           4
           4
           4
相关问题