Terminating OpenMP loop early
-
Another poster already asked similar question already (http://www.codeproject.com/Messages/3644795/What-is-the-best-way-to-break-return-from-OpenMP-l.aspx[^]), but I'll ask anyway. I have a function that checks if a point belongs to an object in array. The loop looks like this:
for (int i=0; i<N; i++)
{
if (point_is_in_object(obj[i], pt){
return true;
}
}
return false;I parallelized it with OpenMP by adding shared boolean flag
found
.bool found = false;
#pragma omp parallel for
for (int i=0; i<N; i++)
{
if (!found)
{
if (point_is_in_object(obj[i], pt){
found = true;
#pragma omp flush (found)
}
}
}return found;
Is this a good way to do this? Could this cause access violation when one thread is writing and the other thread is reading memory contents of
found
flag? I'm new to OpenMP and don't know much how it operates under the hood. With standard Win32 I would isolate access tofound
with critical section. Should I do the same here as well and addcritical
clause? Thanks -
Another poster already asked similar question already (http://www.codeproject.com/Messages/3644795/What-is-the-best-way-to-break-return-from-OpenMP-l.aspx[^]), but I'll ask anyway. I have a function that checks if a point belongs to an object in array. The loop looks like this:
for (int i=0; i<N; i++)
{
if (point_is_in_object(obj[i], pt){
return true;
}
}
return false;I parallelized it with OpenMP by adding shared boolean flag
found
.bool found = false;
#pragma omp parallel for
for (int i=0; i<N; i++)
{
if (!found)
{
if (point_is_in_object(obj[i], pt){
found = true;
#pragma omp flush (found)
}
}
}return found;
Is this a good way to do this? Could this cause access violation when one thread is writing and the other thread is reading memory contents of
found
flag? I'm new to OpenMP and don't know much how it operates under the hood. With standard Win32 I would isolate access tofound
with critical section. Should I do the same here as well and addcritical
clause? ThanksDamir Valiulin wrote:
Could this cause access violation when one thread is writing and the other thread is reading memory contents of found flag?
You are safe the memory barrier MFENCE[^] instruction will be generated by the flush directive. The only change I would suggest is declaring your bool as volatile. This will hint the compiler to generate instructions differently and not bother to keep your bool in a register. Best Wishes, -David Delaune
-
Damir Valiulin wrote:
Could this cause access violation when one thread is writing and the other thread is reading memory contents of found flag?
You are safe the memory barrier MFENCE[^] instruction will be generated by the flush directive. The only change I would suggest is declaring your bool as volatile. This will hint the compiler to generate instructions differently and not bother to keep your bool in a register. Best Wishes, -David Delaune
David, thanks for the quick answer. This was helpful.