OpenMP: single construct

关于 OpenMP 的 single construct,一开始理解存在偏差,相信也是不少新手刚接触OpenMP 时容易犯的一个错误,就是 single construct 能确保每一个区块只由一个thread 完成,但不能保证所有的区块都由不同的 thread 完成,贴上「Using OpenMP」的一段话: >The single construct is associated with the structured block of code immediately following it and specifies that this block should be executed by one thread only.

我是在测试下面的Fortran代码的时候才意识到一开始没仔细看书,理解有所偏差:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
program main
use omp_lib
implicit none
!$omp parallel
!$omp sections
!$omp section
! call fun_1()
print*,"1st section Executed by thread", omp_get_thread_num()
!$omp section
! call fun_2()
print*,"2nd section Executed by thread", omp_get_thread_num()
!$omp end sections
!$omp end parallel
end program main

如果你只运行一次看到类似下面的输出可能会忽略这个理解的偏差:

1
2
1st section Executed by thread 0
2nd section Executed by thread 1

不过我运气比较“好”,第一次运行就是两个 section 都由 thread 0 执行,然后试了三四十次,大概有十分之一的概率出现同一个 thread 执行,不过这个概率并没有什么卵用,知道 single construct 只保证每一个区块只由一个 thread 执行完成就行。其实再往下想想,你的电脑 thread 总数毕竟有限,区块数量大于最大 thread 数量时肯定无法保证每个区块执行的 thread 都不同是吧?