I have a C++ class Runner that encapsulates running a native thread. This class is exposed to Python via pybind11, so start_thread is called from Python.
class Runner {
public:
void start_thread() {
thread_ = std::jthread([]{
try {
while (true) {
// do something
}
} catch (...) {
pybind11::gil_scoped_acquire gil;
pybind11::set_error(PyExc_RuntimeError, "Something horrible happend");
}
});
}
private:
std::jthread thread_;
};
Exception might be thrown in native thread, is there a way to reraise an exception from a native thread to Python?
I was thinking about using pybind11::set_error, but is it the right way? And if so what are the guarantees on when Python realises that there is an exception? If exceptions are checked as soon as Gil is released by a native thread - then this solution should be fine.
std::terminate, I'd hope that reraising exception in Python will allow Python interpreter to gracefully shutdown, calling potentialfinallyblocks. Or if it's non terminal exception, Python could recover from that and restart native thread.std::terminatebecause it's handled by C++ runtime, rather than Python