I have a C++ application in which I use Boost Threads to provide concurrency. The basic sample is as follows:
processingThreadGroup->create_thread(boost::bind(process, clientSideSocket, this));
Here, processingThreadGroup is a shared pointer to a thread pool in boost, and process is the function that I need to call. The clientSideSocket and this are parameters that should be passed to the process function.
Inside the process function, I throw a custom Exception if an error is detected. The process function sends data to a remote server. So my question is, how to I propagate this error up the call stack? I want to shut down the system after a clean up. Tried the following:
try {
processingThreadGroup->create_thread(boost::bind(process, clientSideSocket, this));
} catch (CustomException& exception) {
//code to handle the error
}
But didn’t work. Any idea on how to do this properly?
Thanks!
To propagate return values and exceptions you should use
futures. Here is a simple way to do it:This has a number of gotchas that you have to keep in mind. First, the lifetime of
taskhas to extend the asynchronous execution ofprocess. Second,get()will block until thetaskis finished and return its value if it ended successfully, or propagate the exception if one was thrown. You can use all kind of functions to check the state of thefuture, likehas_value(),has_exception(),is_ready().