How to use a future without waiting for it?
Asked Answered
B

2

6

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.

Belgae answered 4/6, 2017 at 12:16 Comment(1)
Are you looking for something like then and when_all or when_any continuations?Pharisaism
P
4

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.

Potomac answered 4/6, 2017 at 12:28 Comment(0)
G
1

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(); }
Godmother answered 4/6, 2017 at 19:58 Comment(1)
Maybe that is more of the answer OP is helped with... Hint: std::transform futures into calculated_futures to better express intent.Potomac

© 2022 - 2024 — McMap. All rights reserved.