STD :: Promise Set_exception两次导致分段故障
std::promise set_exception twice cause Segmentation fault
假设我有一种调用不稳定第三方服务的方法,所以我添加了此通话的超时,说10秒。这是我尝试的:
int process()
{
std::promise<int> promise;
std::future<int> future = promise.get_future();
std::thread([&]
{
try
{
int result = call_third_party_service();
promise.set_value(result);
}
catch (std::exception&) //call_thrid_party_service can throw exceptions
{
promise.set_exception(std::current_exception());
}
}).detach();
auto status = future.wait_for(std::chrono::seconds(10));
if (status == std::future_status::timeout)
{
promise.set_exception(time_out_exception);
}
return future.get();
}
int main()
{
try
{
int result = process();
}
catch(const std::exception& e)
{
//print
}
//blocks the thread to see what happens
std::this_thread::sleep_for(std::chrono::minutes(1));
return 0;
}
当call_third_party_service
不响应时(假设它会在30秒后抛出一个例外情况(,status == std::future_status::timeout
在等待10秒后命中,然后promise.set_exception
工作,而一切看起来都不错。但是,当call_third_party_service
引发异常时,再次promise.set_exception
,因此分段故障。实施此模式的正确方法是什么?
按照Frax
的建议,您应该将promise
移至lambda中,并在future
乘以时直接抛出异常:
int process() {
std::promise<int> promise;
std::future<int> future = promise.get_future();
// move ownership of the promise into thread
std::thread([prom = std::move(promise)]() mutable {
try {
int result = call_third_party_service();
prom.set_value(result);
} catch (std::exception&) // call_thrid_party_service can throw exceptions
{
prom.set_exception(std::current_exception());
}
}).detach();
auto status = future.wait_for(std::chrono::seconds(10));
if (status == std::future_status::timeout) {
// This exception is not part of an asynchronous computation and
// should be thrown immediately
throw time_out_exception("timed out");
}
return future.get();
}
int main() {
try {
int result = process();
} catch (const std::exception& e) {
// print
}
// blocks the thread to see what happens
std::this_thread::sleep_for(std::chrono::minutes(1));
return 0;
}
相关文章:
- g++的分段错误(在NaN上使用to_string两次时)
- 蛇在C++不会连续转两次
- 检查一个数组是否包含在另一个数组中,以相反的顺序,至少两次
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 我应该如何去缓解两次出现的cin?
- Realloc 两次无法在 Visual Studio 上运行
- 使用 getline(cin, var) 两次在进行字符串比较时会产生错误 (==)
- 为什么映射插入和 map.find() 的单次迭代比插入和 map.find() 的两次单独迭代慢得多
- C++析构函数调用两次,堆栈分配的复合对象
- 为什么参数在构造 std::thread 时移动两次
- Qt插槽调用了两次
- 做 std::用相同的unique_ptr移动两次
- C++两次定义相同的函数会导致错误
- 为什么具有静态存储持续时间的同一内联变量在包含在 VS2017 编译的两个翻译单元中时会构造和销毁两次
- 对于优化级别为 0 的 std::vector,析构函数被调用两次
- 使用柯南打包时如何避免列出两次依赖?
- 为什么要执行两次位移((x >> 4)<< 4)?
- 对结构向量进行两次排序
- 调用某个回调函数两次会导致分段错误:Nan
- STD :: Promise Set_exception两次导致分段故障