什么是期货? [英] What are futures?
问题描述
什么是期货?
推荐答案
有一个有关未来的维基百科文章。简而言之,这是一种使用未知值的方法。然后可以根据需要计算值(延迟评估),并且可以选择与主要计算同时计算。
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 ++示例如下。
说要计算两个数字的和。您可以使用典型的热切实现:
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));
或者您可以使用C ++ 11的 std使用Futures方式:异步
,返回 std :: future
。在这种情况下, add
函数只有在尝试使用尚未计算出的值时才会阻塞(一个人也可以创建一个纯粹的惰性选择)。
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<int> i, future<int> j) { return i.get() + j.get(); }
int sum = add(async(launch::async, [](){ return Nth_prime(4); }),
async(launch::async, [](){ return Nth_prime(2); }));
这篇关于什么是期货?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!