【问题标题】:Usage example of boost::condition::timed_waitboost::condition::timed_wait 的使用示例
【发布时间】:2011-10-28 01:20:14
【问题描述】:

有人有如何最轻松地使用 boost::condition::timed_wait 的示例吗?关于主题hereherehere 有一些主题,但没有一个提供工作示例。而且 boost doc 像往常一样非常稀疏。

【问题讨论】:

  • 这似乎在 boost 中有很好的记录,并且在多线程环境中条件变量的定时等待非常常见。您具体需要什么帮助?
  • @Chad:也许我只是错过了文档?我发现的只是here。那只包含一个非定时样本,即while(!data_ready) { cond.wait(lock); }。对于定时,它只说 timed_wait 的持续时间重载很难正确使用。在大多数情况下,应该首选使用谓词的重载。我不明白这一点,也不是这个 sn-p:while(!pred()) { if(!timed_wait(lock,abs_time)) { return pred(); } } return true;pred() 应该是什么?

标签: c++ multithreading boost boost-thread condition-variable


【解决方案1】:

实际上,我终于找到了完整示例的链接here。稍微适应一下,这似乎是电话。

boost::system_time const timeout=boost::get_system_time()+ boost::posix_time::milliseconds(35000);
boost::mutex::scoped_lock lock(the_mutex);
if(the_condition_variable.timed_wait(lock,timeout,&CondFulfilled))
{
    <cond fulfilled code>
}
else
{
    <timeout code>
}
bool CondFulfilled() { ... }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 2020-07-03
    • 1970-01-01
    • 2011-06-06
    • 2020-11-17
    相关资源
    最近更新 更多