简体   繁体   English

获取 std::future 的状态

[英]Get the status of a std::future

Is it possible to check if a std::future has finished or not?是否可以检查std::future是否已完成? 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?据我所知,唯一的方法是用零持续时间调用wait_for并检查状态是否ready ,但有没有更好的方法?

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; }

NB 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

There's an is_ready member function in the works for std::future. std::future 的工作中有一个 is_ready 成员函数。 In the meantime, the VC implementation has an _Is_ready() member.同时,VC 实现有一个 _Is_ready() 成员。

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 .我的第一个赌注是使用 0 持续时间调用wait_for ,并检查可以是future_status::readyfuture_status::deferredfuture_status::timeout之一的结果代码。

valid() will return true if *this refers to a shared state, independently of whether that state is ready or not.如果*this指的是共享状态,则valid()将返回true ,与该状态是否准备好无关。 See cppreference .请参阅cppreference

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM