异常传播和std::future

Exception propagation and std::future

本文关键字:future std 传播 异常      更新时间:2023-10-16

我的理解是,当异步操作抛出异常时,它将被传播回调用std::future::get()的线程。然而,当这样的线程调用std::future::wait()时,异常不会立即传播——它将在随后调用std::future::get()时被抛出。

然而,在这种情况下,如果future对象在调用std::future::wait()之后超出作用域,但在调用std::future::get()之前,应该发生什么异常?

对于感兴趣的人,这里有一个简单的例子。在这种情况下,异常由thread/future包静默处理:
#include "stdafx.h"
#include <thread>
#include <future>
#include <iostream>
int32_t DoWork( int32_t i )
{
    std::cout << "i ==  " << i << std::endl;
    throw std::runtime_error( "DoWork test exception" );
    return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
    auto f = std::async( DoWork, 5 );
    try
    {
        //f.get();     // 1 - Exception does propagate.
        f.wait();      // 2 - Exception does NOT propagate.
    }
    catch( std::exception& e )
    {
        std::cout << e.what() << std::endl;
        return -1;
    }
    return 0;
}

它被忽略并丢弃,就像您为一个值wait()但从不get()它一样。

wait()只是说"阻塞直到未来准备好",用一个值或异常准备好。这取决于调用者实际get()值(或异常)。通常你只会使用get(),它会等待。