I need to include exception handling into OpenMP and already found Elegant exceptionhandling in OpenMP where this code was suggested:
class ThreadException {
std::exception_ptr Ptr;
std::mutex Lock;
public:
ThreadException(): Ptr(nullptr) {}
~ThreadException(){ this->Rethrow(); }
void Rethrow(){
if(this->Ptr) std::rethrow_exception(this->Ptr);
}
void CaptureException() {
std::unique_lock<std::mutex> guard(this->Lock);
this->Ptr = std::current_exception();
}
};
//...
ThreadException except;
#pragma omp parallel
{
try {
//some possibly throwing code
}
catch(...) { except.CaptureException(); }
}
My question: Is the lock really necessary?
As far as I understand exception_ptr behaves like shared_ptr, which in turn has the thread safty of a raw pointer. So, multiple simultaneous writes are ok.
And if multiple exceptions from different threads come up, I do not care which one ends up in Ptr as long as one does.
Notes: As already pointed out it is not a good idea to do the rethrow in the destructor. I would have asked my question in the comments there, but I don't have the reputation for that.
Aucun commentaire:
Enregistrer un commentaire