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?
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.
for(int i = 0; i < 1000; i++) f.wait_for(chrono::seconds(0));
takes 43ms of wall clock time. –
Libbie wait_until(chrono::system_clock::time_point::min())
you don't need the current time, and it's faster. That optimisation is specific to GCC though, and for GCC 11 you'd need to use steady_clock
instead of system_clock
as we're about to change the clock that is used under the covers. –
Retire f.wait_for(0)
is almost as fast as it is after the future is ready. Less than 100ns. –
Retire There's an is_ready member function in the works for std::future. In the meantime, the VC implementation has an _Is_ready() member.
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.
Since C++11, std::future
now has both a wait()
and a get()
method, which will wait until the future has a valid response, with the latter method waiting (blocking) and then returning a result when it is ready.
If you want to check if it's ready without blocking, then I've done the same as what David Rodríguez - dribeas suggested; call wait_for
with a 0 (or maybe up to 10ms) duration, and check the result code that can be one of future_status::ready
, future_status::deferred
or future_status::timeout
. How short the delay needs to be depends on your needs.
- cppreference: wait_for()
- cppreference: std::future_status
© 2022 - 2025 — McMap. All rights reserved.
valid
only checks if the future has a shared state (i.e. It returnstrue
untilget
is called on the future). – Purismget
has been called and returns the stored value, do you still wanttrue
? (I'm not sure why this would be useful, since you can only get the value once.) – SpooferyQFuture::isFinished
basically. – Purism