gpt4 book ai didi

c++ - boost::shared_future 和 when_all 有多个延续

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

我有一个 DAG 任务,我正在尝试使用 boost::shared_future 框架执行这些任务。

举个具体的例子,考虑图中的data flow graph

enter image description here

下面是对此进行编码的尝试:

#include <iostream>

#define BOOST_THREAD_PROVIDES_FUTURE
#define BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION
#define BOOST_THREAD_PROVIDES_FUTURE_WHEN_ALL_WHEN_ANY
#include <boost/thread/future.hpp>

using namespace boost;

int main() {
shared_future<int> fa = async([]() { sleep(1); return 123; });
shared_future<int> fb = async([]() { sleep(2); return 456; });
shared_future<int> fc = async([]() { sleep(5); return 789; });

auto fabc = when_all(fa,fb,fc);
auto fx = fabc.then([](decltype(fabc)) {
std::cout << "A,B,C has completed, computing X\n";
return 1;
});
auto fax = when_all(fa,std::move(fx));
auto fz = fax.then([](decltype(fax)) {
std::cout << "A,X has completed, computing Z\n";
return 2;
});
auto fcx = when_all(fc,std::move(fx)); // <---- BAD
auto fy = fcx.then([](decltype(fcx)) {
std::cout << "C,X has completed, computing Y\n";
return 3;
});
fy.get();
fz.get();
}

但是,这不起作用(显然,因为我在 fx 上调用了两次 std::move)。我想问题是 - 有没有办法让 when_allthen 返回“共享”类型,以便明智地执行?或者 task-DAG 的执行是否超出了 boost 的极限?

最佳答案

喜欢 T.C.也就是说,您可以通过调用 share() 成员函数来分享您的 future 。这样你就不需要移动两次:

Live On Coliru

#include <iostream>

#define BOOST_THREAD_PROVIDES_FUTURE
#define BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION
#define BOOST_THREAD_PROVIDES_FUTURE_WHEN_ALL_WHEN_ANY
#include <boost/thread/future.hpp>

using namespace boost;
using boost::this_thread::sleep_for;
using boost::chrono::milliseconds;

int main() {
shared_future<int> fa = async([]() { sleep_for(milliseconds(100)); return 123; });
shared_future<int> fb = async([]() { sleep_for(milliseconds(200)); return 456; });
shared_future<int> fc = async([]() { sleep_for(milliseconds(500)); return 789; });

auto fabc = when_all(fa, fb, fc);

auto fx = fabc
.then([](decltype(fabc)) { std::cout << "A,B,C has completed, computing X\n"; return 1; })
.share();
auto fax = when_all(fa, fx);

auto fz = fax
.then([](decltype(fax)) { std::cout << "A,X has completed, computing Z\n"; return 2; })
.share();
auto fcx = when_all(fc, fx);

auto fy = fcx
.then([](decltype(fcx)) { std::cout << "C,X has completed, computing Y\n"; return 3; })
.share();

fy.get();
fz.get();
}

打印

A,B,C has completed, computing X
C,X has completed, computing Y
A,X has completed, computing Z

关于c++ - boost::shared_future 和 when_all 有多个延续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35249961/

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