简体   繁体   中英

C++ How to Catch a Exception Thrown by a Thread in Boost from the Thread-Spawning Function

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 future s. Here is a simple way to do it:

// R is the return type of process, may be void if you don't care about it
boost::packaged_task< R > task( boost::bind(process, clientSideSocket, this) );
boost::unique_future< R > future( task.get_future() );

processingThreadGroup->create_thread(task);

future.get();

This has a number of gotchas that you have to keep in mind. First, the lifetime of task has to extend the asynchronous execution of process . Second, get() will block until the task is 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 the future , like has_value() , has_exception() , is_ready() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM