朋友们,我正在尝试学习 openMP 范例。
我使用以下代码来理解#omp for pragma。
int main(void){
int tid;
int i;
omp_set_num_threads(5);
#pragma omp parallel \
private(tid)
{
tid=omp_get_thread_num();
printf("tid=%d started ...\n", tid);
fflush(stdout);
#pragma omp for
for(i=1; i<=20; i++){
printf("t%d - i%d \n",
omp_get_thread_num(), i);
fflush(stdout);
}
printf("tid=%d work done ...\n", tid);
}
return 0;
}
在上面的代码中,#pragma omp parallel 末尾有一个隐式屏障,这意味着所有线程 0,1,2,3,4 必须到达那里才能进入下一条语句。
因此,为了检查这个障碍,我将这个“pragma for”包含在条件 if(tid!=0) 中,这意味着除线程 0 之外的所有线程(即 1、2、3、4)都应该在循环中完成其工作并等待 thread0无限期地。但是,令我惊讶的是,这并没有发生。每个线程都在进行迭代并成功完成。即 t1 完成迭代 5,6,7,8 ---- t2 完成 9,10,11,12 ---- t3 完成 13,14,15,16,t4 完成 17,18,19,20。请注意:迭代 1、2、3、4 从未完成。
为了更深入地挖掘,我在 tid!=1 中包含了相同的 #pragma for in tid!=1,而不是 tid!=0,这意味着 thread1 绕过了屏障,而不是 thread0。令我惊讶的是,程序现在挂起,所有线程都在等待 thread1。
有人可以告诉我这种意外行为的解释吗?最终挂起的代码:
int main(void){
int tid;
int i;
omp_set_num_threads(5);
#pragma omp parallel \
private(tid)
{
tid=omp_get_thread_num();
printf("tid=%d started ...\n", tid);
fflush(stdout);
if(tid!=1){
/* worksharing */
#pragma omp for
for(i=1; i<=20; i++){
printf("t%d - i%d \n",
omp_get_thread_num(), i);
fflush(stdout);
}
}else{
printf("t1 reached here. \n");
}
printf("tid=%d work done ...\n", tid);
}
return 0;
}
我尝试设置共享或私有,但它并没有改变程序的行为。