Reputation: 638
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?
Upvotes: 2
Views: 853
Reputation: 74455
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 aparallel
region must cause execution to resume within the sameparallel
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.
Upvotes: 3