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

2019-03-23 01:15发布

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?

2条回答
姐就是有狂的资本
2楼-- · 2019-03-23 01:58

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.

查看更多
淡お忘
3楼-- · 2019-03-23 01:59

you can use ._Is_ready() now. Instead of waiting.

Yes I know this question is old but though it needed updating as I stumbled on it today

查看更多
登录 后发表回答