Reputation: 34175
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?
Upvotes: 26
Views: 12474
Reputation: 4519
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.
Upvotes: 23