Skip to content

3.8 Joining futures

Alexander Damian edited this page Aug 21, 2019 · 3 revisions

Joining futures

Working with futures is easy when you only need to deal with a single one at a time. Managing multiple concurrent futures can however become a complex task, especially if the caller task needs to wait on all the results before proceeding further.

Traditionally the approach would be to store all futures inside a container such as a vector and once all async tasks are dispatched, to loop over the vector checking all futures for completion. The FutureJoiner utility class provides exactly such abstraction. It converts from a vector<future<T>> to a future<vector<T>> which allows the user to wait on a single future and retrieve all values at once in one atomic operation.

The FutureJoiner class

    //Start with a vector of futures
    std::vector<ThreadContextPtr<int>> futures;
    
    //Create a bunch of async tasks...
    for (int i = 0; i < 10; ++i) {
        futures.push_back(dispatcher.post([i](CoroContext<int>::Ptr ctx)->int {
            // do something and then return a value
            return ctx->set(i);
        }));
    }
    
    //Group async results into a single future value
    std::vector<int> output = FutureJoiner<int>()(dispatcher, std::move(futures))->get();