I am having an issue handling exceptions in multithreaded c++ code. The following program exits with 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();
}
}
Instead, I would like to handle the exception in the try catch
block in main()
. I understand that exceptions are not (normally) passed between threads since threads each have there own stack. The issue here (it seems to me) is that the exception is not being handled even though it is being generated on the non-forked thread. If I comment out the lines in run()
having to do with control_thread
, everything works fine.
Compiled with clang-3.8 and -std=c++11 main.cpp -lpthread
.