c++如何从线程生成函数中捕获Boost中线程抛出的异常

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

本文关键字:线程 异常 Boost 函数 c++      更新时间:2023-10-16

我有一个c++应用程序,在这个应用程序中我使用Boost Threads来提供并发性。基本示例如下:

processingThreadGroup->create_thread(boost::bind(process, clientSideSocket, this));

这里,processingThreadGroup是boost中指向线程池的共享指针,process是我需要调用的函数。clientSideSocket和this是应该传递给流程函数的参数。

在进程函数中,如果检测到错误,则抛出自定义Exception。process函数将数据发送到远程服务器。我的问题是,如何在调用堆栈中传播这个错误?我想在清理后关闭系统。尝试如下:

try {
    processingThreadGroup->create_thread(boost::bind(process, clientSideSocket, this));
} catch (CustomException& exception) {
    //code to handle the error
}

但没有工作。有什么好办法吗?

谢谢!

要传播返回值和异常,您应该使用future s。这里有一个简单的方法:

// 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();

这有很多你必须记住的陷阱。首先,task的生存期必须延长process异步执行。其次,get()将阻塞直到task完成,如果成功结束则返回其值,如果抛出异常则传播异常。您可以使用各种函数来检查future的状态,如has_value(), has_exception(), is_ready()