异常传播和std :: future [英] Exception propagation and std::future
问题描述
std :: future :: get()
的线程。然而,当这样的线程调用 std :: future :: wait()
时,异常不会立即传播 - 它会抛出一个随后的调用 std :: future :: get()
。 但是,在这种情况下,如果未来对象在调用 std后超出范围,则会发生这种异常:: future :: wait()
,但在调用 std :: future :: get()
之前?
对于那些感兴趣的人,这里是一个简单的例子。在这种情况下,异常由线程/未来程序包静默处理:
#includestdafx.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 - 异常确实传播。
f.wait(); // 2 - 异常不传播。
}
catch(std :: exception& e)
{
std :: cout< e.what()< std :: endl;
return -1;
}
return 0;
}
就像你 wait()
为一个值,但从不 get()
it。
wait()
简单地说阻塞,直到未来准备就绪,准备好一个值或异常。这取决于调用者实际上 get()
的值(或异常)。通常你只需使用 get()
,它仍然会等待。
My understanding is that when an asynchronous operation throws an exception, it will be propagated back to a thread that calls std::future::get()
. However, when such a thread calls std::future::wait()
, the exception is not immediately propagated - it'll be thrown upon a subsequent call to std::future::get()
.
However, In such a scenario, what is supposed to happen to such an exception if the future object goes out of scope after a call to std::future::wait()
, but prior to a call to std::future::get()
?
For those interested, here is a simple example. In this case, the exception is silently handled by the thread/future package:
#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;
}
It is ignored and discarded, just like if you wait()
for a value but never get()
it.
wait()
simply says "block until the future is ready", be that ready with a value or exception. It's up to the caller to actually get()
the value (or exception). Usually you'll just use get()
, which waits anyway.
这篇关于异常传播和std :: future的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!