gpt4 book ai didi

c++ - future 的可组合性,以及 boost::wait_for_all

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:24:44 26 4
gpt4 key购买 nike

我刚刚阅读了文章“Futures Done Right” ',而 c++11 promises 缺少的主要内容似乎是从现有的 composite futures 中创建

我现在正在查看 boost::wait_for_any 的文档

但请考虑以下示例:

int calculate_the_answer_to_life_the_universe_and_everything()
{
return 42;
}

int calculate_the_answer_to_death_and_anything_in_between()
{
return 121;
}

boost::packaged_task<int> pt(calculate_the_answer_to_life_the_universe_and_everything);
boost:: future<int> fi=pt.get_future();
boost::packaged_task<int> pt2(calculate_the_answer_to_death_and_anything_in_between);
boost:: future<int> fi2=pt2.get_future();

....


int calculate_the_oscillation_of_barzoom(boost::future<int>& a, boost::future<int>& b)
{
boost::wait_for_all(a,b);
return a.get() + b.get();
}

boost::packaged_task<int> pt_composite(boost::bind(calculate_the_oscillation_of_barzoom, fi , fi2));
boost:: future<int> fi_composite=pt_composite.get_future();

这种可组合性方法有什么问题?这是实现可组合性的有效方法吗?我们需要一些优雅的句法来修饰这种模式吗?

最佳答案

when_anywhen_all是构成 future 的完全有效的方式。它们都对应于并行组合,其中组合操作等待一个或所有组合操作。

我们还需要顺序组合(Boost.Thread 中没有)。例如,这可能是 future<T>::then允许您排队使用 future 值(value)并在未来准备就绪时运行的操作的功能。可以自己实现,但需要权衡效率。 Herb Sutter 在他的 recent Channel9 video 中谈到了这一点.

N3428是将这些功能(以及更多)添加到 C++ 标准库的提案草案。它们都是库的特性,不会向该语言添加任何新语法。此外,N3328是为可恢复函数 添加语法的提议(例如在 C# 中使用 async/await),它将使用 future<T>::then内部。

关于c++ - future 的可组合性,以及 boost::wait_for_all,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14170287/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com