带有break语句的并行OpenMP循环

时间:2012-03-20 19:45:11

标签: c++ multithreading loops openmp

我知道你不能有一个OpenMP循环的break语句,但我想知道是否有任何解决方法,同时仍然受益于并行性。基本上我有'for'循环,循环遍历大向量的元素,寻找满足某个条件的一个元素。但是只有一个元素可以满足条件,所以一旦发现我们可以突破循环,提前谢谢

for(int i = 0; i <= 100000; ++i)
  {
    if(element[i] ...)
     {
          ....
          break;
      }
   }

5 个答案:

答案 0 :(得分:19)

请参阅此代码段:

volatile bool flag=false;

#pragma omp parallel for shared(flag)
for(int i=0; i<=100000; ++i)
{    
    if(flag) continue;
    if(element[i] ...)
    {
          ...
          flag=true;
    }
}

这种情况更适合pthread。

答案 1 :(得分:7)

您可以尝试使用while循环手动执行openmp for循环:

const int N = 100000;
std::atomic<bool> go(true);
uint give = 0;

#pragma omp parallel
{
    uint i, stop;

    #pragma omp critical
    {
        i = give;
        give += N/omp_get_num_threads();
        stop = give;

        if(omp_get_thread_num() == omp_get_num_threads()-1)
            stop = N;
    } 


    while(i < stop && go)
    {
        ...
        if(element[i]...)
        {
            go = false;
        }
        i++;
    }
}

这种方式你必须在每个周期测试“go”,但这不应该那么重要。更重要的是,这将对应于循环的“静态”omp,这仅在您可以预期所有迭代花费相似的时间量时才有用。否则,3个线程可能已经完成,而其中一个仍然有一半...

答案 2 :(得分:2)

我可能会做(从yyfn复制一下)

volatile bool flag=false;

for(int j=0; j<=100 && !flag; ++j) {
  int base = 1000*j;
  #pragma omp parallel for shared(flag)
  for(int i = 0; i <= 1000; ++i)
  {

    if(flag) continue;
    if(element[i+base] ...)
     {
          ....
          flag=true;
      }
   }
}

答案 3 :(得分:0)

bool foundCondition = false;
#pragma omp parallel for
for(int i = 0; i <= 100000; i++)
{
    // We can't break out of a parallel for loop, so this is the next best thing.
    if (foundCondition == false && satisfiesComplicatedCondition(element[i]))
    {
        // This is definitely needed if more than one element could satisfy the
        // condition and you are looking for the first one.  Probably still a
        // good idea even if there can only be one.
        #pragma omp critical
        {
            // do something, store element[i], or whatever you need to do here
                ....

            foundCondition = true;
        }
    }
}

答案 4 :(得分:0)

以下是接受答案的简单版本。

int ielement = -1;
#pragma omp parallel
{
    int i = omp_get_thread_num()*n/omp_get_num_threads();
    int stop = (omp_get_thread_num()+1)*n/omp_get_num_threads();        
    for(;i <stop && ielement<0; ++i){
        if(element[i]) {
            ielement = i;
        }
    }
}