c++ - C++ 破承诺异常
问题描述
我正在学习std::async
并遇到broken_promise
异常。
但是,以下示例代码似乎不会导致损坏的承诺异常。我的理解是,当promise被销毁,future还在等待的时候,应该抛出异常。但是,在我的代码中,调用future.get()
会永远等待。
不应该调用 promise 的析构函数并在 lambda 完成时抛出异常吗?
int main()
{
std::promise<int> prom;
std::future<int> fut = prom.get_future();
auto retFut = std::async(std::launch::async, [prom = std::move(prom)] () mutable {
cout << "In child" << endl;
//prom.set_value(4); <-- Shouldn't not having this line cause the exception
});
int childValue = fut.get();
cout << "Child has set the value: " << childValue << endl;
return 0;
}
甚至是这个孩子期望得到承诺的项目
void DoSomething(std::future<int>&& fut)
{
cout << "Waiting for parent to send a value " << endl;
int val = fut.get();
cout << "Parent sent value " << val << endl;
}
int main()
{
std::promise<int> prom;
std::future<int> fut = prom.get_future();
auto retFut = std::async(std::launch::async, DoSomething, std::move(fut));
// prom.set_value(3); <-- This should cause the exception?
return 0;
}
解决方案
主要问题是正在等待错误的未来。
你在等待
int childValue = fut.get();
当你应该等待时
int childValue = retFut.get();
话虽这么说,std::async
是最好避开的 C++ 的一部分。在实践中,它很少交付,在复杂的项目中最好使用某种任务池,例如cpp-taskflow
.
推荐阅读
- reactjs - 接收套接字消息的最佳位置是什么?[React、Redux、Web 套接字]
- c++ - C ++:strcpy非ascii字符问题可能吗?
- ios - 什么是 SwiftUI 中的 UIView readableContentGuide 等价物
- hadoop - 如何在配置单元中获取时间戳('yyyy-mm-dd hh:mm:ss')的平均值(平均值)?
- angular - 如何将角度 8 中的多个图像上传到 asp .net 核心
- xml - 使用 FLWOR 的机器人
- corda - 哪里可以得到神经图-
.jar 用于社区版的 Corda 网络设置? - ruby-on-rails - Rails:正在加载 wkhtmltopdf-binary-edge gem 中的 wkhtmltopdf 可执行文件
- arrays - 我可以将带有空格分隔符的字符串字段转换为mongoDB聚合中的数组吗
- python-3.x - 使用 python 生产代码将文本文件保存到远程文件服务器