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

标签 c++ multithreading boost c++11 future

我刚刚阅读了文章“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/

相关文章:

c++ - 使用新的Valgrind中的内存泄漏

c++ - 用于 C++ 持续集成的 buildbot vs hudson/jenkins

c++ - 当协程切换线程时,如何强制 Linux 上的 g++ 更新线程指针(用于 TLS)?

c++ - 将缓冲区 boost 为 char*(无 std::string)

c++ - "No viable overloaded ' = ' "为什么?

std::pair 和前向声明的 C++ 问题

java - 为什么 Java 中的用户级线程称为 "green"?

java - 服务器套接字中的线程和处理程序

c++ - Boost::Log 使用具有多个接收器的相同后端的安全性

boost - 安装FastCGI++