c++multithreadingloopsopenmp

Parallel OpenMP loop with break statement


I know that you cannot have a break statement for an OpenMP loop, but I was wondering if there is any workaround while still the benefiting from parallelism. Basically I have 'for' loop, that loops through the elements of a large vector looking for one element that satisfies a certain condition. However there is only one element that will satisfy the condition so once that is found we can break out of the loop, Thanks in advance

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

Solution

  • You could try to manually do what the openmp for loop does, using a while loop:

    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++;
        }
    }
    

    This way you have to test "go" each cycle, but that should not matter that much. More important is that this would correspond to a "static" omp for loop, which is only useful if you can expect all iterations to take a similar amount of time. Otherwise, 3 threads may be already finished while one still has halfway to got...