Reputation: 122133
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.
Upvotes: 6
Views: 905
Reputation: 64308
The design of futures lends itself to this kind of solution, where you create more futures representing the calculated values:
std::vector<std::future<int>> calculated_futures;
for (auto &e : futures) {
calculated_futures.push_back(
std::async([&e]{ return someLengthyCalculation(e.get()); })
);
}
int sum = 0;
for(auto &e : calculated_futures) { sum += e.get(); }
Upvotes: 1
Reputation: 41509
You are right that the current future
library is not complete yet. What we miss is a way to indicate 'when future x is ready, start operation f'. Here's a nice post about that.
What you may want is a map/reduce implementation: upon each future's completion, you want to start adding it to the accumulator (reduce).
You can use a library for that - it's not very simple to build it yourself :). One of the libraries that's gaining traction is RxCpp - and they have a post on map/reduce.
Upvotes: 4