3

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...

parsley72
  • 8,449
  • 8
  • 65
  • 98
LearnMore
  • 695
  • 1
  • 5
  • 12
  • 1
    What's the `0` for in your call to `std::async`? – Holt May 15 '18 at 10:02
  • 1
    Have you considered using a callback timer? See this answer: https://stackoverflow.com/questions/12904098/c-implementing-timed-callback-function – stack user May 15 '18 at 10:02
  • @Holt I thought the issue was somehow related to **std::async**'s args, so added the 0 in an attempt to make it work...as it liked **void** even less. – LearnMore May 15 '18 at 10:21

2 Answers2

4

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).

Holt
  • 36,600
  • 7
  • 92
  • 139
1

Because refresh_data is a method of Log you need to use std::bind with model_log, or use a lambda:

std::future<bool> retCode = std::async( [this] {return model_log.refresh_data(); }); 
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122