给定以下源代码
#include <thread>
#include <future>
#include <iostream>
#include <string>
#include <chrono>
int main() {
auto task = std::async(std::launch::async, [] {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
throw std::runtime_error("error");
});
try {
while (task.wait_for(std::chrono::seconds(0)) !=std::future_status::ready)
{
std::cout << "Not ready: " << std::endl;
}
task.get();
}
catch (const std::exception& e)
{
std::cout << "Valid: " << task.valid() << std::endl;
}
}我想,这个程序会用Valid: 0来响应。使用g++ 6.2.0是这样的。但是,使用MS VS2015版本14.0.25431.01更新3,响应是Valid: 1。在将异常传播到主线程之后,未来的状态不会失效。这是一个错误,还是我在这里遇到了未定义的行为?
发布于 2017-03-07 12:42:12
我好像是个虫子。
根据 documentation的说法,valid()应该在调用get之后返回false。
任何共享状态都会被释放。在调用此方法后,
valid()是false。
深入了解一下VC++实现get,就会发现一个bug:
virtual _Ty& _Get_value(bool _Get_only_once)
{ // return the stored result or throw stored exception
unique_lock<mutex> _Lock(_Mtx);
if (_Get_only_once && _Retrieved)
_Throw_future_error(
make_error_code(future_errc::future_already_retrieved));
if (_Exception)
_Rethrow_future_exception(_Exception);
_Retrieved = true;
_Maybe_run_deferred_function(_Lock);
while (!_Ready)
_Cond.wait(_Lock);
if (_Exception)
_Rethrow_future_exception(_Exception);
return (_Result);
}基本上,如果_Retreived持有true,那么_Exception也应该被设置为exception_ptr。在抛出时,这个变量从未设置过。看起来,当他们测试它时,他们并没有为一个现成的未来进行测试,而只是为了不成熟的未来进行测试,因为后者不会显示这个bug。
https://stackoverflow.com/questions/42648352
复制相似问题