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

China☆狼群 提交于 2019-12-09 05:15:03

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/14287127/how-to-check-if-a-stdasync-task-is-finished

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!