Get the status of a std::future

C++MultithreadingC++11Future

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

You are correct, and apart from calling wait_until with a time in the past (which is equivalent) there is no better way.

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.

Solution 2 - C++

There's an is_ready member function in the works for std::future. In the meantime, the VC implementation has an _Is_ready() member.

Solution 3 - C++

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.

valid() will return true if *this refers to a shared state, independently of whether that state is ready or not. See cppreference.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid BrownView Question on Stackoverflow
Solution 1 - C++Jonathan WakelyView Answer on Stackoverflow
Solution 2 - C++Rick YorgasonView Answer on Stackoverflow
Solution 3 - C++David Rodríguez - dribeasView Answer on Stackoverflow