The following example is taken from a C++ async tutorial:
#include <future>
#include <iostream>
#include <vector>
int twice(int m) { return 2 * m; }
int main() {
std::vector<std::future<int>> futures;
for(int i = 0; i < 10; ++i) { futures.push_back (std::async(twice, i)); }
//retrive and print the value stored in the future
for(auto &e : futures) { std::cout << e.get() << std::endl; }
return 0;
}
How can I use the result of a future
without waiting for it? Ie I would like to do something like this:
int sum = 0;
for(auto &e : futures) { sum += someLengthyCalculation(e.get()); }
I could pass a reference to the future
to someLengthyCalculation
, but at some point I have to call get
to retrieve the value, thus I dont know how to write it without waiting for the first element being completed, before the next one can start summing.
then
andwhen_all
orwhen_any
continuations? – Pharisaism