Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a future without waiting for it?

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.

like image 930
463035818_is_not_a_number Avatar asked Jun 04 '17 12:06

463035818_is_not_a_number


People also ask

How do you use the Future in darts?

A future (lower case “f”) is an instance of the Future (capitalized “F”) class. A future represents the result of an asynchronous operation, and can have two states: uncompleted or completed. Note: Uncompleted is a Dart term referring to the state of a future before it has produced a value.

What is a Future in c++?

A future is an object that can retrieve a value from some provider object or function, properly synchronizing this access if in different threads. "Valid" futures are future objects associated to a shared state, and are constructed by calling one of the following functions: async.

What does Future mean in flutter?

A Future class permits you to run work asynchronously to let loose whatever other threads ought not to be obstructed. Like the UI thread. In this blog, we will Explore Futures In Flutter. We will see how to use the future in your flutter applications.


1 Answers

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.

like image 95
xtofl Avatar answered Oct 23 '22 05:10

xtofl