为什么当OMP并行段中的while循环在终止条件取决于来自不同段的更新时无法终止 [英] Why does while loop in an OMP parallel section fail to terminate when termination condition depends on update from different section

查看:646
本文介绍了为什么当OMP并行段中的while循环在终止条件取决于来自不同段的更新时无法终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++代码是否合法,或者我的编译器有问题吗?使用

Is the C++ code below legal, or is there a problem with my compiler? The code was complied into a shared library using

gcc版本4.4.6 20110731(Red Hat 4.4.6-3)(GCC)将代码编译到共享库

gcc version 4.4.6 20110731 (Red Hat 4.4.6-3) (GCC)

和openMP,然后通过R 2.15.2调用。

and openMP and then called via R 2.15.2.

int it=0;
#pragma omp parallel sections shared(it)
   {
      #pragma omp section
      {
           std::cout<<"Entering section A"<<std::endl;
           for(it=0;it<10;it++)
           {
                   std::cout<<"Iteration "<<it<<std::endl;

           }
           std::cout<<"Leaving section A with it="<<it<<std::endl;
      }

      #pragma omp section
      {
           std::cout<<"Entering section B with it="<<it<<std::endl;
           while(it<10)
           {
                   1;
           }
           std::cout<<"Leaving section B"<<std::endl;
  }
}

我获得以下输出2个线程,但我认为它是可解释的):

I obtain the following output (apologies for interweaving output from 2 threads but I think it is interpretable):

Entering section A
Iteration Entering section B with it=0
0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Iteration 6
Iteration 7
Iteration 8
Iteration 9
Leaving section A with it=10

程序然后摊位:B部分似乎卡在了while循环。因为变量'it'是共享的,我不明白为什么while循环不会在部分A完成时终止。

The program then stalls: section B seems to get stuck in the while loop. Since the variable 'it' is shared I do not understand why the while loop doesn't terminate when section A is complete.

推荐答案

这是因为 shared 变量只意味着它对所有线程都是一样的,但是程序员仍然必须手动同步访问

That is because shared variable only means it it the same for all threads, but programmer still has to synchronize access by hands

共享条款

程序员有责任确保多个线程正确访问SHARED变量(例如通过CRITICAL部分)

It is the programmer's responsibility to ensure that multiple threads properly access SHARED variables (such as via CRITICAL sections)

因此,您可以在第一部分完成后 flush 变量:

So, you can, for example, flush variables after first section is completed:

      #pragma omp section
      {
           std::cout<<"Entering section A"<<std::endl;
           for(it=0;it<10;it++)
           {
                   std::cout<<"Iteration "<<it<<std::endl;

           }
           #pragma omp flush(it)
           std::cout<<"Leaving section A with it="<<it<<std::endl;
      }

      #pragma omp section
      {
           std::cout<<"Entering section B with it="<<it<<std::endl;
           while(it<10)
           {
            #pragma omp flush(it)
                   1;
           }
           std::cout<<"Leaving section B"<<std::endl;
      }

这篇关于为什么当OMP并行段中的while循环在终止条件取决于来自不同段的更新时无法终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆