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?
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.
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.
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.
Use future::wait_for()
. You can specify a timeout, and after that, get a status code.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With