一个Windows平台下Fortran多线程程序的诡异结果

laughcry2002 2014-07-14 08:52:18
一个openmp多线程程序出现的异常结果。最小的示例代码附后。平台:Windows 7 (64 bit), Intel Fortran 编译器(版本附后)

代码 : test_omp.f90


module my_omp_mod
use omp_lib
implicit none
public

integer :: idt, num_threads

contains

subroutine init()
implicit none

num_threads = omp_get_num_threads()
idt = omp_get_thread_num()

write(*, *) "in init(): idt, num_threads = ", idt, num_threads, omp_get_thread_num()
end subroutine

end module

program main
use omp_lib
use my_omp_mod
implicit none

integer :: idt2, num_threads2

!$OMP parallel default(none) private(idt2, num_threads2) private(idt, num_threads)

call init()
write(*, *) "in main(): idt, num_threads = ", idt, num_threads, omp_get_thread_num()

num_threads2 = omp_get_num_threads()
idt2 = omp_get_thread_num()
write(*, *) "in main(): idt2, num_threads2 = ", idt2, num_threads2, omp_get_thread_num()

!$OMP end parallel
end program


编译:

引用
D:\>ifort -openmp test_omp.f90
Intel(R) Visual Fortran Compiler XE for applications running on IA-32, Version 14.0.2.176 Build 20140130
Copyright (C) 1985-2014 Intel Corporation. All rights reserved.

Microsoft (R) Incremental Linker Version 9.00.21022.08
Copyright (C) Microsoft Corporation. All rights reserved.

-out:test_omp.exe
-subsystem:console
-defaultlib:libiomp5md.lib
-nodefaultlib:vcomp.lib
-nodefaultlib:vcompd.lib
test_omp.obj


运行:
引用
D:\>set OMP_NUM_THREADS=2

D:\>test_omp.exe
in init(): idt, num_threads = 0 2 0
in main(): idt, num_threads = 0 0 0
in main(): idt2, num_threads2 = 0 2 0
in init(): idt, num_threads = 1 2 1
in main(): idt, num_threads = 0 0 1
in main(): idt2, num_threads2 = 1 2 1


异常出在 module 中定义的 idt 变量取值,在 openmp 指导语句中声明为 private 了,但结果似乎表明在 main 中各线程共享了同一个值(而在 init() 内却是正常的)。

谁能帮忙解释一下?
...全文
314 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

566

社区成员

发帖
与我相关
我的任务
社区描述
英特尔® 边缘计算,聚焦于边缘计算、AI、IoT等领域,为开发者提供丰富的开发资源、创新技术、解决方案与行业活动。
社区管理员
  • 英特尔技术社区
  • shere_lin
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧