0

我有一个像这样的代码:

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)
    {

    }
}

如果在第二个未来抛出异常,我只会在第一个未来完成时收到它。有没有办法中断所有的期货?

4

1 回答 1

0

这些功能需要协调停止自己,例如 cancel_token 之类的东西。按照设计,您不能从外部中止线程。

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;
        }
    }    
}
于 2020-08-27T15:24:53.063 回答