【发布时间】:2013-02-19 06:17:25
【问题描述】:
我有一个程序需要将异常从任何未捕获的线程传播到主线程,以便它可以向用户提供有关它失败的原因并安全关闭的信息。我的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);
}
【问题讨论】:
-
你的类在 GNU/Linux 上与 GCC 一起工作得很好(在将
count()更改为size()并将调用更改为非标准std::exception构造函数并将Semaphore替换为std::condition_variable之后) 所以这听起来像是一个 MSVC 错误。线程是由main线程还是由其他线程产生的,这无关紧要。 -
在vs2013上能用吗?
-
是否适用于VS2015或VS2017?
标签: c++ multithreading exception c++11 visual-studio-2012