2

I am trying to speed up a specific part of a large program, the exception handling is done at high level, originally the code looks like

for(....)
{
...
   if(...)
   {
    throw std:: runtime_error("Terminated by user")
   }
}

Now I have changed it to something like

#pragma omp parallel for ...
for(....)
{
...
   if(...)
   {
    throw std:: runtime_error("Terminated by user")
   }
}

And now if termination is triggered, the program crashes, I am expecting this exception handling here can be done in an elegant way without changing the higher level stuff?

lorniper
  • 626
  • 1
  • 7
  • 29
  • Possible duplicate of [Elegant exceptionhandling in OpenMP](http://stackoverflow.com/questions/11828539/elegant-exceptionhandling-in-openmp) – Adri C.S. Aug 03 '16 at 08:21

1 Answers1

3

The OpenMP specification mandates that exceptions thrown by some thread must be handled by the same thread and within the same parallel region (Section 2.5, p. 49):

A throw executed inside a parallel region must cause execution to resume within the same parallel region, and the same thread that threw the exception must catch it.

Compilers like GCC enforce this requirement by wrapping the code of the parallel region with a catch-all construct similar to this:

try
{
   ...
}
catch
{
   terminate();
}

Thus, any exception that reaches the end of the parallel region uncaught will cause the program to abort.

The rule is actually stricter as it also applies to OpenMP constructs such as for, critical, single, etc. An exception thrown within such a construct must be caught within the same construct and by the thread that threw it. In your case, it is the for construct that results in the termination as its implicit catch-all handler is reached before the implicit catch-all handler of the parallel region.

Hristo Iliev
  • 72,659
  • 12
  • 135
  • 186
  • So I have to catch this exception within pragma for and propagate it to higher level? – lorniper Aug 03 '16 at 08:39
  • Yes, you can do it with an explicit try/catch block or think of a more elegant approach like the one outlined in the question linked to by Adri C.S. – Hristo Iliev Aug 03 '16 at 10:17