C++;如何从线程生成函数捕获Boost中线程引发的异常 我有一个C++应用程序,在这里我使用Boost线程来提供并发。基本样本如下: processingThreadGroup->create_thread(boost::bind(process, clientSideSocket, this));

C++;如何从线程生成函数捕获Boost中线程引发的异常 我有一个C++应用程序,在这里我使用Boost线程来提供并发。基本样本如下: processingThreadGroup->create_thread(boost::bind(process, clientSideSocket, this));,c++,exception,boost,exception-handling,boost-thread,C++,Exception,Boost,Exception Handling,Boost Thread,这里,processingThreadGroup是指向boost中线程池的共享指针,process是我需要调用的函数。clientSideSocket和这是应该传递给process函数的参数 在process函数中,如果检测到错误,我会抛出一个自定义异常。process功能将数据发送到远程服务器。所以我的问题是,如何将这个错误传播到调用堆栈中?我想在清理后关闭系统。尝试了以下操作: try { processingThreadGroup->create_thread(boost::

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

在process函数中,如果检测到错误,我会抛出一个自定义异常。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();
//R是进程的返回类型,如果您不关心它,它可能是空的
boost::packaged_task任务(boost::bind(进程,clientSideSocket,this));
boost::unique_futurefuture(task.get_future());
processingThreadGroup->创建线程(任务);
future.get();

这有许多你必须记住的问题。首先,
任务
的生命周期必须延长
进程
的异步执行。其次,
get()。您可以使用各种函数来检查
未来的状态,例如
具有值()
具有异常()
已准备就绪()
它看起来非常像
std::async
所做/可能做的,它使用
未来的
来处理返回值和异常。谢谢您的建议。我是boost的新手,将阅读futures。@Izza:你发布的代码不是真正的代码,是吗?
bind
调用将尝试创建套接字的副本…clientSideSocket只是用于标识套接字的整数。所以我不认为这是个问题。