我已经尝试使用boost::shared_future
框架执行任务的DAG。
例如具体性,请考虑图中所示的data flow graph。
这是尝试对此进行编码:
#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();
}
然而,这不起作用(显然,因为我在std::move
上两次呼叫fx
)。我想问题是 - 有没有办法让when_all
和then
返回&#34;共享&#34;类型,以便明智地执行?或者任务-DAG执行是否超出了提升可以做的限制?
答案 0 :(得分:3)
像T.C.说,您可以通过调用share()
成员函数分享您的未来。这样你就不需要移动两次了:
<强> 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