Defined in <stlab/concurrency/future.hpp>
template <typename E, typename F, typename...Ts>
auto when_any(E e, F f, future<Ts>... args)
(1)
template <typename E, typename F, typename I> 
auto when_any(E e, F f, const std::pair<I,I>& range)
(2)

Creates a future that continues on the first success of any futures passed. The results of all passed futures must be convertible to the first parameter of the continuing function. The function must accept the a second parameter of std::size_t. It will receive the index of the future that succeeded first.

  1. This function create a future that continues whenever the first future of the passed arguments args succeeds.

  2. This function create a future that continues whenever the first future within the range succeeds

Parameters

e

Executor which is used to schedule the resulting task

f

Callable object that implements the task

args

Futures that shall be joined

range

This describes the range of futures. If an empty range is provided then a stlab::future_exception with code stlab::future_errc::broken_promise is thrown.

Return value

a future that reduces a number of input futures to the first that successds and passes it to the associated function object

Example 1

#include <iostream>
#include <string>
#include <thread>
#include <stlab/concurrency/default_executor.hpp>
#include <stlab/concurrency/future.hpp>

using namespace std;
using namespace stlab;

int main() {
    auto argument1 = async(default_executor, [] { return 42; });
    auto argument2 = async(default_executor, [] { return 815; });

    auto result = when_any(default_executor, [](int x, std::size_t index) {
        cout << "The current result is " << x << " " << index << '\n';
    }, argument1, argument2);

    // Waiting just for illustrational purpose
    while (!result.get_try()) { this_thread::sleep_for(chrono::milliseconds(1)); }
}

/*
    Result:

        The current result is 42 0
        or 
        The current result is 815 1
*/

Example 2

#include <iostream>
#include <string>
#include <thread>
#include <stlab/concurrency/default_executor.hpp>
#include <stlab/concurrency/immediate_executor.hpp>
#include <stlab/concurrency/future.hpp>
#include <stlab/concurrency/utility.hpp>


using namespace std;
using namespace stlab;

int main() {
    auto fv = []{
        return stlab::make_ready_future(immediate_executor);
    };

    auto f = when_any(stlab::default_executor, [](size_t index){
        std::cout << "f: " << index << '\n';
    }, fv(), fv(), fv(), fv(), fv(), fv());

    while (!f.get_try()) std::this_thread::sleep_for(std::chrono::milliseconds(1));
}

/*
    Result: (index number may vary)

        f: 0
*/