c++如何从线程生成函数中捕获Boost中线程抛出的异常
C++ How to Catch a Exception Thrown by a Thread in Boost from the Thread-Spawning Function
我有一个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()
。
相关文章:
- 异常属于C++中的线程还是进程
- 是什么导致了Unity 3D中的"错误线程异常"?
- C++线程库异常
- zeromq 在 I/O 线程中引发异常
- 如果不包含 pthread,为什么 GCC 的线程标准库实现会抛出异常?
- SIGABRT 和线程相关的异常,但在调试期间工作正常
- C++子线程抛出异常
- 防止线程在处理异常后在分离时调用 std::terminate()
- 多线程异常和锁定
- 线程中的异常 "main" java.lang.UnsatisfiedLinkError: no JNTIest in java.library.path
- STD ::线程和异常处理
- 终止无效异常(多线程合并排序)
- 当不调用thread.join()时,C 多线程异常
- 联接线程时出现异常
- 如何使用QThreads使无锁生产者-消费者线程交换更加异常安全
- 异常不会使用boost :: future/boost :: Promise跨线程正确传播
- JNI : 线程"AWT-EventQueue-0" java.lang.UnsatisfiedLinkError 中的异常
- 将 C# 窗口句柄传递给非托管代码 - 跨线程异常
- C++跨线程异常引发
- c++同步和跨线程异常处理