I'd like to run tasks (worker threads) of the same type, but not more than a certain number of tasks at a time. When a task finishes, its result is an input for a new task which, then, can be started.
Is there any good way to implement this with async/future paradigm in C++11?
At first glance, it looks straight forward, you just spawn multiple tasks with:
std::future<T> result = std::async(...);
and, then, run result.get()
to get an async result of a task.
However, the problem here is that the future objects has to be stored in some sort of queue and be waited one by one. It is, though, possible to iterate over the future objects over and over again checking if any of them are ready, but it's not desired due to unnecessary CPU load.
Is it possible somehow to wait for any future from a given set to be ready and get its result?
The only option I can think of so far is an old-school approach without any async/future. Specifically, spawning multiple worker threads and at the end of each thread push its result into a mutex-protected queue notifying the waiting thread via a condition variable that the queue has been updated with more results.
Is there any other better solution with async/future possible?
when_any(futures...).then(foo)
, but for now, you're kinda out of luck. – Xeowhen_any
here. Boost's wait_for_any is exactly what I'm looking for. AFAIU, it's not compatible with std::future which does not support registration of external waiters (cvs), right? – alvekospawning multiple worker threads and at the end of each thread push its result into a mutex-protected queue
sounds fine to me. You don't even need the notification if the worker thread simply checks for a queue size ≥ 1 once in a while. – Lightness Races in Orbitwhen_any
/.then(...)
made it into C++14. I think they're headed for the Concurrency TS that was kicked off in Chicago. – je4d