我有自己的线程类,旨在帮助安全地管理异常。它看起来像这样:(为了简单起见,跳过了其他构造函数和互斥体)
class ExceptThread
: public std::thread {
public:
template<typename Func, typename... Args>
ExceptThread(Func&& f, Args&&... args)
: std::thread([] (Args&&... args) {
try {
return f(args...);
} catch(...) {
exc = std::current_exception();
}
}, args...) { }
// skipped other constructors etc.
//...
void check() {
if(exc) {
std::exception_ptr tmp = exc;
exc = nullptr;
std::rethrow_exception(tmp);
}
}
private:
std::exception_ptr exc;
};
这个类的用法如下:
ExceptThread et([] { std::this_thread::sleep_for(5s); throw std::runtime_error("Ugly exception"); });
try {
while(/*...*/) {
// main loop
et.check();
}
} catch(std::exception& e) {
// do sth
}
Problem:
当线程抛出异常时,它会被捕获catch(...)
并保存到exc
, 一切安好。但当执行更进一步std::terminate
就像没有捕获异常一样被调用。我还尝试暂停子线程(例如Sleep(INFINITE)
) 捕获异常后但是std::terminate()
在分离线程时被调用std::thread::~thread()
在主线程中堆栈展开期间。我怎样才能阻止系统这样做?
平台:MSVC
相似的:如何在线程之间传播异常? https://stackoverflow.com/questions/233127/how-can-i-propagate-exceptions-between-threads
您必须在销毁线程之前显式加入线程,这有助于防止在销毁线程之前忘记中断线程时潜在的死锁/崩溃(在我使用的每个实现中,std::terminate 消息中都说明了这一点) 。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)