What are futures?

后端 未结 7 1202
长发绾君心
长发绾君心 2021-02-13 09:37

What are futures? It\'s something to do with lazy evaluation.

7条回答
  •  时光说笑
    2021-02-13 10:19

    There is a Wikipedia article about futures. In short, it's a way to use a value that is not yet known. The value can then be calculated on demand (lazy evaluation) and, optionally, concurrently with the main calculation.

    C++ example follows.


    Say you want to calculate the sum of two numbers. You can either have the typical eager implementation:

    int add(int i, int j) { return i + j; }
    // first calculate both Nth_prime results then pass them to add
    int sum = add(Nth_prime(4), Nth_prime(2)); 
    

    or you can use the futures way using C++11's std::async, which returns an std::future. In this case, the add function will only block if it tries to use a value that hasn't yet been computed (one can also create a purely lazy alternative).

    int add(future i, future j) { return i.get() + j.get(); }
    int sum = add(async(launch::async, [](){ return Nth_prime(4); }),
                  async(launch::async, [](){ return Nth_prime(2); }));
    

提交回复
热议问题