Using boost::future with “then” continuations

后端 未结 4 1559
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-24 12:35

The C++ 11 std::future lacks a then method to attach continuations to the future.

The Boost boost::future provides this, and t

4条回答
  •  眼角桃花
    2020-12-24 13:20

    There may be a faster and easier way to use continuations than std::future or boost::future. Both of them have been criticized for being slow due to several reasons. See e.g. this presentation.

    The solution proposed in the presentation is implemented in github as a header-only library. You can chain any number of continuations and avoid implicit heap allocations. Also exceptions can be caught normally.

    Here is an example where two sets of continuations are run in parallel:

    #include 
    #include 
    #include 
    
    #include "Lazy.h"
    
    int main()
    {
        int iInput = 10;
    
        // Future #1: input an integer, then take square root, then convert double to string
        auto f = Lazy::future(iInput).
                    then([](auto x) { return std::sqrt(double(x)); }).
                    then([](auto x) { return std::to_string(x); }).
                    finalize();
    
        // Future #2: input an integer, then square it, then convert int to string
        auto g = Lazy::future(iInput).
                    then([](auto x){ return x*x; }).
                    then([](auto x){ return std::to_string(x);}).
                    finalize();
    
        // Launch the tasks...
        std::cout << "Calling f.run...\n";
        auto f_run = f.run();
        std::cout << "Calling g.run...\n";
        auto g_run = g.run();
    
        // Do something else while f and g are running...
        // ... then get the results.
        try {
            std::string strSqrt = f.get(f_run);
            std::string strSquare = g.get(g_run);
    
            std::cout << "Future f returned " << strSqrt << "\n";
            std::cout << "Future g returned " << strSquare << "\n";
        }
        catch (...) {
            // Deal with an exception here.
        }
    }
     /* Output:
    Calling f.run...
    Calling g.run...
    Future f returned 3.162278
    Future g returned 100
    */
    

提交回复
热议问题