【问题标题】:Execute function in C++ after asynchronous 60 sec delay?在异步 60 秒延迟后在 C++ 中执行函数?
【发布时间】:2018-10-25 02:48:29
【问题描述】:

我读过这可以使用 std::this_thread::sleep_forstd::async 来实现,但它不适合我。

这里是要调用的函数:

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;
}

从另一个函数调用。下面的代码中有两个使用失败的例子:

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 );
}

最初,bool Log::r​​efresh_data()void Log::r​​efresh_data()std::async 似乎不是喜欢 void 返回...

【问题讨论】:

  • 你打电话给std::async时的0是什么意思?
  • 你考虑过使用回调定时器吗?看到这个答案:stackoverflow.com/questions/12904098/…
  • @Holt 我认为这个问题在某种程度上与 std::async 的参数有关,因此添加了 0 以使其正常工作......因为它喜欢void 甚至更少。

标签: c++ stdasync


【解决方案1】:

你不能在 C++ 中传递这样的非静态方法,你可以这样做:

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

这些代码使用 void 返回类型(您只需删除 lambda 中的 return 语句)。

【讨论】:

    【解决方案2】:

    因为refresh_dataLog 的方法,您需要将std::bindmodel_log 一起使用,或者使用lambda:

    std::future<bool> retCode = std::async( [this] {return model_log.refresh_data(); }); 
    

    【讨论】:

      猜你喜欢
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 1970-01-01
      • 2015-12-06
      • 1970-01-01
      相关资源
      最近更新 更多