c++stdasync

Execute function in C++ after asynchronous 60 sec delay?


I've read this can be achieved using std::this_thread::sleep_for and std::async, but it's not working for me.

Here is the function to be called:

bool Log::refresh_data()
{   

    std::this_thread::sleep_for( std::chrono::minutes( 1 ) );

    std::vector<std::string> file_info = this->file.read_pending_if();

    for( auto line : file_info )
    {
        this->append( line );
    }

    return true;
}

Which is called from another function. There are two examples of failed usage in the code below:

void MVC::refresh_data()
{
    // Error C3867  'Log::refresh_data': non-standard syntax; use '&' to create a pointer to member
    std::future<bool> retCode = std::async( this->model_log.refresh_data, 0 );        
    std::future<bool> retCode = std::async( this->model_log.refresh_data(), 0 );
}

Originally, bool Log::refresh_data() was void Log::refresh_data() but std::async didn't seem to like the void return...


Solution

  • You cannot pass a non-static method like this in C++, you can do:

    auto retCode = std::async(&Log::refresh_data, model_log);
    // Or with a lambda:
    auto retCode = std::async([this]() { 
        return model_log.refresh_data(); 
    });
    

    These codes work with a void return type (you simply need to remove the return statement in the lambda).