STD ::期货和例外
std::futures and exception
本文关键字:STD 更新时间:2023-10-16
给定以下源代码
#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
。例外传播到主线程后,未来的状态并未无效。这是一个错误还是我在这里遇到未定义的行为?
我似乎是一个错误。
根据std::future::get
文档,valid()
应在致电get
后返回false
。
任何共享状态都会发布。
valid()
是呼叫此方法后的false
。
在get
的VC 实现中进行一些挖掘,那里有一个错误:
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);
}
基本上,如果_Exception
持有exception_ptr
,也应将_Retreived
设置为true
。到投掷时,这个变量永远不会设置。看来,当他们测试它时,他们没有为未来的未来测试,仅适用于未准备的未来,因为后者不会显示此错误。
相关文章:
- 没有找到相关文章