2016-02-07 55 views
4

我有一個DAG的任務,我試圖執行使用boost::shared_future框架。boost :: shared_future和多個延續when_all

例如具體,請考慮圖中所示的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返回「共享」類型,以便它明智地執行?或者是任務DAG的執行超出了可以做什麼的限制?

+2

如果你想 「共享」,使用'.share()'? –

回答

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