我有一个程序需要将异常从任何未捕获的线程传播到主线程,以便它可以向用户提供有关它失败的原因并安全关闭的信息。我的InterThreadException
处理程序似乎工作,但只有当抛出异常的线程由主线程直接产生时。
处理程序在所有情况下InterTheadException
都被正确调用,通过将异常指针传递给它来发出异常传播的信号,并且主线程接收到它已收到新异常的通知,但std::rethrow_exception
对异常指针的调用只是失败了并且似乎什么都不做。我已经测试过从这两个不同的线程中抛出完全相同的异常,无论我抛出什么问题似乎都仍然存在。
我怀疑我对应该如何使用异常指针有一个基本的误解,但我不确定。
这是我的InterThreadExceptionHandler
.
class InterThreadExceptionHandler : NonCopyable
{
public:
InterThreadExceptionHandler();
~InterThreadExceptionHandler();
//
// Sends an exception into this handler, informing it that
//this exception has been caught
// and may be propagated to another thread
//
void sendException(std::exception_ptr exception);
//
// Freezes the calling thread until an exception has been sent,
//then rethrows said exception
//
void waitForException();
private:
std::vector<std::exception_ptr> sentExceptions;
std::mutex sentExceptionsMutex;
Semaphore sentExceptionsCounter;
};
InterThreadExceptionHandler::InterThreadExceptionHandler()
{
}
InterThreadExceptionHandler::~InterThreadExceptionHandler()
{
}
void InterThreadExceptionHandler::sendException(std::exception_ptr exception)
{
ScopedLock lock(this->sentExceptionsMutex);
this->sentExceptions.push_back(exception);
this->sentExceptionsCounter.give();
}
void InterThreadExceptionHandler::waitForException()
{
this->sentExceptionsCounter.take();
ScopedLock lock(this->sentExceptionsMutex);
assert( this->sentExceptions.size() > 0 );
std::exception_ptr e = this->sentExceptions[0];
this->sentExceptions.erase(this->sentExceptions.begin());
if (e == std::exception_ptr())
{
throw std::exception("Invalid exception propagated!");
}
std::rethrow_exception(e);
}