2

I want to run a series of C++11 threads (std::thread) such that each thread can return a value to the process that created it.

I got some idea as to how to do this here.

However, when using std::future, according to this, the execution is blocked until the value is ready. When I have multiple threads, I would like to use the return values of each thread as they become available, instead of accessing them in the order determined by the order in which the value from the future is obtained.

For example, if I have threads t1, t2, and t3, and I obtain their results as

t1.get();
t2.get();
t3.get();

then, I am potentially waiting till t1 has its result ready, even if t2 and t3 have completed their tasks.

Is there a way to overcome this?

Community
  • 1
  • 1
GoodDeeds
  • 7,956
  • 5
  • 34
  • 61
  • @HiI'mFrogatto Could you please show how? – GoodDeeds Jan 08 '17 at 11:49
  • [This `std::future` reference](http://en.cppreference.com/w/cpp/thread/future) might be helpful. You can always use e.g. [`wait_for`](http://en.cppreference.com/w/cpp/thread/future/wait_for) with a zero duration to poll the future. – Some programmer dude Jan 08 '17 at 11:51
  • [Callback functions in c++](http://stackoverflow.com/q/2298242/327083) – J... Jan 08 '17 at 11:52
  • Or better still with a non-zero duration. – Martin Bonner supports Monica Jan 08 '17 at 11:53
  • @Someprogrammerdude So do you suggest that I have a loop running, with each iteration checking if any future is ready, and running till as long as all of them are ready? – GoodDeeds Jan 08 '17 at 11:56
  • @MartinBonner Thank you for the link. It somehow didn't show up in the Google search as well as in the Ask Question suggestions. – GoodDeeds Jan 08 '17 at 11:58
  • 1
    I'm not saying it's a good idea, just a possible solution. :) The answer from user2079303 is a much better solution. – Some programmer dude Jan 08 '17 at 11:59
  • 1
    As explained in the duplicate, there is a suitable technical specification. direct link: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0159r0.html#futures.when_any – DaveFar Jan 08 '17 at 12:16

1 Answers1

3

Your problem is a generalized version of the produced-consumer problem where you have multiple producers and a single consumer.

You simply need to use a queue that is shared by all threads. The producer threads push values into the queue, and the consumer (the main thread) pops the data in order that they were pushed. You must synchronize the access to the queue.

eerorika
  • 232,697
  • 12
  • 197
  • 326