omp single
指定在当前的并行域里当前代码块只被执行一次(任意线程均可)
用法:
#pragma omp single [clause,clause , ...] |
参数:
clause | Can be one or more of the following clauses:
|
当在主从模式使用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子句。