0

I have a code like:

std::vector<std::future<..>> futures;
for(...)
{
    futures.emplace_back(std::async(std::launch::async, ...))
}
for (auto& future : futures)
{
    try
    {
        result += future.get();
    }
    catch (std::exception const& e)
    {

    }
}

If an exception is thrown in second future I will receive it only when the first future will be done. Is there a way to interrupt all futures?

w00drow
  • 468
  • 2
  • 11
  • 1
    You need to implement that yourself in the functions your `future`s are associated with, so they return or throw early if something went wrong. For example, they could all have a reference to a shared `std::atomic` which can be set when something goes wrong. – François Andrieux Aug 27 '20 at 14:27
  • You might find [this](https://ichef.bbci.co.uk/images/ic/480xn/p04znpm3.jpg) useful. – hnefatl Aug 27 '20 at 14:46

1 Answers1

0

The functions need to co-ordinate stopping themselves, e.g. something like cancellation_token. By design you can't abort a thread from the outside.

concurrency::cancellation_token_source token_source;
for (...)
{
    futures.emplace_back(std::async(std::launch::async, ..., token_source.get_token()))
}

while(!futures.empty())
{
    for (auto it = futures.begin(); it != futures.end();) 
    {
        if(it->wait_for(0s) == std::future_status::ready) 
        {
            try 
            {
                result += it->get();
            }
            catch (...) 
            {
                token_source.cancel();
            }
            it = futures.erase(it);
        } 
        else 
        {
            ++it;
        }
    }    
}
Caleth
  • 52,200
  • 2
  • 44
  • 75