C++ 获取 std::future 的状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10890242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the status of a std::future
提问by David Brown
Is it possible to check if a std::future
has finished or not? As far as I can tell the only way to do it would be to call wait_for
with a zero duration and check if the status is ready
or not, but is there a better way?
是否可以检查 astd::future
是否已完成?据我所知,唯一的方法wait_for
是以零持续时间调用并检查状态是否ready
存在,但有没有更好的方法?
回答by Jonathan Wakely
You are correct, and apart from calling wait_until
with a time in the past (which is equivalent) there is no better way.
你是对的,除了wait_until
用过去的时间(相当于)打电话外,没有更好的方法。
You could always write a little wrapper if you want a more convenient syntax:
如果您想要更方便的语法,您可以随时编写一个小包装器:
template<typename R>
bool is_ready(std::future<R> const& f)
{ return f.wait_for(std::chrono::seconds(0)) == std::future_status::ready; }
N.B. if the function is deferred this will never return true, so it's probably better to check wait_for
directly in the case where you might want to run the deferred task synchronously after a certain time has passed or when system load is low.
注意,如果函数被延迟,这将永远不会返回 true,因此,wait_for
如果您可能希望在经过特定时间后或系统负载较低时同步运行延迟任务,则最好直接检查。
回答by Rick Yorgason
There's an is_ready member function in the worksfor std::future. In the meantime, the VC implementation has an _Is_ready() member.
std::future的工作中有一个 is_ready 成员函数。同时,VC 实现有一个 _Is_ready() 成员。
回答by David Rodríguez - dribeas
My first bet would be to call wait_for
with a 0 duration, and check the result code that can be one of future_status::ready
, future_status::deferred
or future_status::timeout
.
我的第一个赌注wait_for
是以 0 持续时间调用,并检查可以是future_status::ready
,future_status::deferred
或之一的结果代码future_status::timeout
。
In cppreferencethey claim that valid()
checks if the result is available, but the standard says that valid()
will return true
if *this
refers to a shared state, independently of whether that state is readyor not.
在cppreference 中,他们声称valid()
检查结果是否可用,但标准说如果引用共享状态,valid()
则将返回,与该状态是否准备好无关。true
*this