Get std :: future status

Is it possible to check if std::future finished or not? As far as I can tell, the only way to do this is to call wait_for with a zero duration and check if the status is ready or not, but is there a better way?

+49
c ++ multithreading c ++ 11 future
Jun 05 2018-12-06T00:
source share
3 answers

You are right, and besides calling wait_until with time in the past (which is equivalent), there is no better way.

You can always write a small 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, it will never return true, so it is better to check wait_for directly if you can run the deferred task synchronously after a certain time or at low system load.

+36
Jun 06 2018-12-06T00:
source share

There is a member_ready function in the works for std :: future. In the meantime, the VC implementation has a member of _Is_ready ().

+7
May 4 '14 at
source share

My first bet would be to call wait_for with a duration of 0 and check the result code, which can be one of future_status::ready , future_status::deferred or future_status::timeout .

In cppreference, they claim that valid() checks to see if the result is available, but the standard says that valid() will return true if *this refers to the general state, whether that state is ready or not.

+6
Jun 05 2018-12-12T00:
source share



All Articles