当终止条件取决于来自不同部分的更新时,为什么OMP并行部分中的while循环无法终止 C++下面的代码是合法的,还是我的编译器有问题?该代码被编译成一个共享库,使用

当终止条件取决于来自不同部分的更新时,为什么OMP并行部分中的while循环无法终止 C++下面的代码是合法的,还是我的编译器有问题?该代码被编译成一个共享库,使用,c++,for-loop,while-loop,openmp,C++,For Loop,While Loop,Openmp,gcc版本4.4.6 20110731(红帽4.4.6-3)(gcc) 和openMP,然后通过R2.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++)

gcc版本4.4.6 20110731(红帽4.4.6-3)(gcc)

和openMP,然后通过R2.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;
  }
}

然后程序暂停:B部分似乎卡在while循环中。由于变量“it”是共享的,我不理解为什么while循环在A部分完成时不终止。

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

程序员有责任确保多个线程正确地访问共享变量(例如通过关键部分)

例如,您可以在第一部分完成后使用变量:

      #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;
      }
#pragma omp部分
{

std::coutAs一个有趣的问题是,在部分a中添加flush命令是否严格必要?是否所有数据都从处理器缓存复制到部分末尾的主内存中?
      #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;
      }