我正在学习std::async,并遇到了broken_promise异常。
但是,下面的示例代码似乎不会导致破坏承诺异常。我的理解是,当承诺被摧毁而未来仍在等待时,应该抛出异常。然而,在我的代码中,对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;
}发布于 2020-06-07 06:11:21
主要的问题是错误的未来被等待着。
你在等待
int childValue = fut.get();当你应该等待的时候
int childValue = retFut.get();话虽如此,std::async是C++的一部分,最好避开它。在实践中,它很少交付,在复杂的项目中,最好使用某种类型的任务池,例如cpp-taskflow。
https://stackoverflow.com/questions/62238337
复制相似问题