我有一个处理多线程C++代码中的异常的问题。以下程序以terminate called without an active exception Aborted (core dumped)
退出。std ::线程和异常处理
#include <thread>
#include <iostream>
#include <stdexcept>
struct Thing {
void runComponent()
{
throw std::runtime_error("oh no!\n");
}
void runController()
{
while (true) {}
}
void run()
{
auto control_thread = std::thread([this] { runController(); });
runComponent();
if (control_thread.joinable())
control_thread.join();
}
};
int main()
{
try {
Thing thing;
thing.run();
} catch (std::runtime_error &ex) {
std::cerr << ex.what();
}
}
相反,我想处理异常的try catch
块main()
。我知道异常不会(通常)在线程之间传递,因为线程每个都有自己的堆栈。这里的问题(在我看来)是即使在非分叉线程上生成异常也没有被处理。如果我注释掉run()
与control_thread
有关的行,那么一切正常。
与铿锵-3.8和-std=c++11 main.cpp -lpthread
编译。
@Curious也许。我知道'exception_ptr'。但这里的问题(我认为)是thrower(runComponent)实际上是在主线程上。即使在这种情况下,我是否需要使用异常指针? – jonnew
在下面的答案中回答!我误解了这个问题 – Curious