异常传播和std::future
Exception propagation and std::future
我的理解是,当异步操作抛出异常时,它将被传播回调用std::future::get()
的线程。然而,当这样的线程调用std::future::wait()
时,异常不会立即传播——它将在随后调用std::future::get()
时被抛出。
然而,在这种情况下,如果future对象在调用std::future::wait()
之后超出作用域,但在调用std::future::get()
之前,应该发生什么异常?
#include "stdafx.h"
#include <thread>
#include <future>
#include <iostream>
int32_t DoWork( int32_t i )
{
std::cout << "i == " << i << std::endl;
throw std::runtime_error( "DoWork test exception" );
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
auto f = std::async( DoWork, 5 );
try
{
//f.get(); // 1 - Exception does propagate.
f.wait(); // 2 - Exception does NOT propagate.
}
catch( std::exception& e )
{
std::cout << e.what() << std::endl;
return -1;
}
return 0;
}
它被忽略并丢弃,就像您为一个值wait()
但从不get()
它一样。
wait()
只是说"阻塞直到未来准备好",用一个值或异常准备好。这取决于调用者实际get()
值(或异常)。通常你只会使用get()
,它会等待。
相关文章:
- 架构决策:返回std::future还是提供回调
- std::p romise::set_value() 和 std::future::wait() 是否提供内存围栏?
- 修改在 std::future 的 lambda 中引用捕获的值
- 从 T 创建 std::future 的最佳方式<T>
- C++ std::future没有被调用
- 对于等待以 std::future wait() 返回的函数的 CPU 使用率或检查标志在循环中休眠一段时间哪个更好?
- 如何使用 boost::future 重新抛出 std::exception_ptr 存储的原始异常?
- Make zmqpp::socket::connect a std::future
- std::future可以比std::promise活得更长吗
- std::future::get()或std::future::wait()是std::thread::join()的替
- 当 std::future 准备好被检索时发出信号主线程
- C++ std::future 方法应该<T>命名为 is_ready() 还是 ready()?
- 当多次调用时,"std::future::then"的行为是什么?
- 使用 std::vector<std::future<int>> 和 std::async 启动几个线程时中止
- 使用 std::future 的不完整类型无效使用
- 为什么 std::future::wait_for 的行为不符合预期?
- 是什么给了 std::future 一些共享状态
- STD :: Future no_state异常与断言
- std::future<nboth:::Both<int, std::string>> 分段错误
- Using std::future/std::async