指定在当前的并行域里当前代码块只被执行一次(任意线程均可)
#pragma omp single [clause,clause , ...]
clause
Can be one or more of the following clauses:
copyprivate(list)
Provides a mechanism to use a private variable in list to broadcast a value from the data environment of one implicit task to the data environments of the other implicit tasks belonging to the parallel region.
firstprivate(list)
Provides a superset of the functionality provided by the private clause. Each private data object is initialized with the value of the original object.
nowait(integer expression)
Indicates that an implementation may omit the barrier at the end of the worksharing region.
private(list)
Declares variables to be private to each thread in a team.
当在主从模式使用single制导语句时,由于有条件分支,因此需要加上nowait语句(必须),否则程序会一直等所有线程同步而导致程序无法往下运行。
如下程序:
int main() { int data, flag = 0; #pragma omp parallel num_threads(2) { if (omp_get_thread_num()==0) { data = 42; #pragma omp single nowait { int i=0; } } else if (omp_get_thread_num()==1) { #pragma omp flush(flag, data) while (flag < 1) { #pragma omp flush(flag, data) } printf("flag=%d data=%d\n", flag, data); #pragma omp flush(flag, data) printf("flag=%d data=%d\n", flag, data); } } return 0; }如果omp single后面没有nowait,则程序不会跳出并行区,会一直在omp single结构化块结束的位置等待所有线程同步。
总结:omp single 在条件分支内部使用的时候,一定要加上nowait子句。