Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the status of a std::future

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?

like image 515
David Brown Avatar asked Jun 05 '12 00:06

David Brown


People also ask

Is std :: future copyable?

3) std::future is not CopyConstructible.

What is std :: future in C++?

std::future A future is an object that can retrieve a value from some provider object or function, properly synchronizing this access if in different threads. "Valid" futures are future objects associated to a shared state, and are constructed by calling one of the following functions: async. promise::get_future.

Is std :: future thread safe?

std::shared_futureAccess to the same shared state from multiple threads is safe if each thread does it through its own copy of a shared_future object.

How do you create a future in C++?

How to create a future ? The simplest way is to use std::async that will create an asynchronous task and return a std::future . Nothing really special here. std::async will execute the task that we give it (here a lambda) and return a std::future .


1 Answers

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.

like image 163
Jonathan Wakely Avatar answered Sep 26 '22 18:09

Jonathan Wakely