【发布时间】:2017-05-13 09:15:12
【问题描述】:
我在处理多线程 C++ 代码中的异常时遇到问题。以下程序以terminate called without an active exception Aborted (core dumped) 退出。
#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();
}
}
相反,我想处理main() 中try catch 块中的异常。我知道异常不会(通常)在线程之间传递,因为每个线程都有自己的堆栈。这里的问题(在我看来)是异常没有被处理,即使它是在非分叉线程上生成的。如果我将run() 中与control_thread 相关的行注释掉,一切正常。
使用 clang-3.8 和 -std=c++11 main.cpp -lpthread 编译。
【问题讨论】:
-
@Curious 也许。我知道
exception_ptr。但是这里的问题(我认为..)是 thrower (runComponent) 实际上在主线程上。即使在这种情况下,我还需要使用异常指针吗? -
在下面的答案中回答!我误解了这个问题
标签: c++ multithreading exception