Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a std::async task is finished?

Tags:

In my graphics application I want to generate a batch meshes in another thread. Therefore I asynchrony call the member function using std::async.

task = async(launch::async, &Class::Meshing, this, Data(...)); 

In my update loop I try to check if the thread is ready. If yes, I will send the mesh to the video card and start the next thread. If not, I will skip these operations.

#include <future> using namespace std;  class Class { public:     void Update()     {         if(task.finished()) // this method does not exist         {             Data data = task.get();             // ...             task = async(launch::async, &Class::Meshing, this, Data(/* ... */));         }     }  private:     struct Data     {         // ...     };     future<Data> task;     Data Meshing(Data data)     {         // ...     } }; 

How can I check if the asynchrony thread finished without stucking in the update function?

like image 284
danijar Avatar asked Jan 11 '13 21:01

danijar


People also ask

How do I know if async task is completed?

You can return a Task or Task<T> and use that to determine if it's completed. Also you can use a CancellationToken and cooperative cancellation to cancel previous tasks. Right now async void is unawawaitable and fire-and-forgot so you won't have any idea if it's done or failed etc.

What is std :: async?

async( std::launch policy, Function&& f, Args&&... args ); (since C++20) The function template async runs the function f asynchronously (potentially in a separate thread which might be a part of a thread pool) and returns a std::future that will eventually hold the result of that function call.

Does STD async use thread pool?

For now, we know that if no policy is specified, then std::async launches a callable function in a separate thread. However, the C++ standard does not specify whether the thread is a new one or reused from a thread pool. Let us see how each of the three implementations launches a callable function.


1 Answers

Use future::wait_for(). You can specify a timeout, and after that, get a status code.

Example:

task.wait_for(std::chrono::seconds(1)); 

This will return future_status::ready, future_status::deferred or future_status::timeout, so you know the operation's status. You can also specify a timeout of 0 to have the check return immediately as soon as possible.

like image 127
lethal-guitar Avatar answered Oct 12 '22 00:10

lethal-guitar