I’m wondering if it is safe to throw an C++ exception inside an OMP critical section.
#pragma omp critical (my_critical_section)
{
...
throw my_exception("failed")
...
}
g++ does not complain. I’m puzzled because it complains about return statements inside the critical section. It returns the error: invalid exit from OpenMP structured block when I write
#pragma omp critical (my_critical_section)
{
...
return;
...
}
So, why is it OK to leave the critical section with an exception, but it is not OK to leave it with a return statement?
No, it is not OK to leave a critical section with exceptions.
g++does not complain in this case but it silently inserts an implicittry/catcharound the block of the critical section. For example the following code:gets lowered by the OpenMP processor of GCC 4.7 into:
Reaching the implicit built-in catch-all handler
<<<eh_must_not_throw (terminate)>>>results in quite ungraceful termination:The implicit
try/catchis inserted regardless of the presence of an outertry/catchconstruct, i.e. the exception would never ever leave thecriticalsection.The OpenMP standard mandates, that if an exception is thrown within most OpenMP constructs (
parallel,section,master,single,for,critical,task, etc.), execution must resume within the same construct and that the same thread must catch the exception. Violation of this restriction leads to non-conformant OpenMP code andg++simply enforces the conformance by insertingtry/catchblocks with termination handlers inside all such constructs.As for the error when a
returnstatement is present, OpenMP defines a strcutured block in C/C++ as:and also (for all languages):
Obviously
returnconstitutes a branch ouf of the block, different from simply falling of the bottom of the block.