OpenMP not supporting break in loop
-
01-06-2021 - |
Question
I am optimizing some code with OpenMP. If NO_VALUE
is met in a loop, I would like it to break. However, compiler tells me this is not allowed with openMP. How could I handle this?
#pragma omp parallel
{
#pragma omp for reduction(+:functionEvaluation) schedule(dynamic) nowait
for (int j=m_colStart;j<m_colEnd+1;j++)
{
double d = command_->execute().toDouble();
if(d==NO_VALUE)
{
functionEvaluation = NO_VALUE;
break;
}
else
{
functionEvaluation += d;
}
delete command_;
}
}
How could I work around? thanks!
Solution
There is no problem with Qt.
you cannot have a break in a loop that has been parallelized using openMP.
Reasoning behind this : Lets say you have a loop with 10 iterations. Now, you want to break the loop at iteration 5. You say,
if (iteration==5)
break;
Now come to the parallel context, you have created 10 threads and each do their respective iteration in parallel. So when thread5 reaches certain condition you want all other threads to
- determine this
- undo their output
- Do not process anymore iterations
- do this dynamically and for all different scheduling policies.
as you can see, this is not possible/practical in most circumstances. Hence OpenMP has disallowed the use of break in a parallel for loop.
Now, say you know that a certain condition for breaking is very rare in your loop and you are hell bent on having a break in your parallel loop.
Thread i
Check input condition
If input leads to breaking flag a marker break_loop
******** barrier across all threads *************
if flag break_loop is true
then
discontinue this operation
mark a variable
discontinue all the remaining iterations
endif
do your normal work
This is just a framework. You will have to look at corner cases, locks, etc. For this you can have each thread check their input before iteration. If their input condition leads to breaking of loop, they set a con
OTHER TIPS
openmp doesn't support break in for clause.
I'm adding this as a proper answer; think about this: you got a loop with a condition to stop, for instance: for(int a=0; a<10; a++) ...
if, while in the loop, you just set a to 9, and execute a continue
statement, it will break out the loop implicitly.