I have a non-blocking function (it returns immediately) that creates a new thread to parse some data:
boost::any Parse() throw(ParseException) {
// parse something
}
typedef void (*HandlerFunc)(boost::any result);
void ParseAsync(HandlerFunc handler) {
Parser me(*this);
in_new_thread {
boost::any result = me.Parse();
handler(result);
}
}
The problem is that Parse can throw an exception. What is the usual C++ way of handling these exceptions? Should I in some way “hand over” the exception to the handler function?
The new C++11 standard support a number of facilities to ease thread programming.
The most interesting, in your case, are
std::futureandstd::promise.Note the
std::promise::set_exception_*function. It allows you to channel an exception outside of its thread of origin (notestd::exception_ptrhas a shared pointer semantics). You can usestd::current_exception()(in acatchstatement) to get the required pointer.Then note the
std::future::getfunction: if thepromisethefutureis extracted from had an exception instead of a value, then it will throw the exception.This is the mechanism in place to channel exceptions from one thread to another.