使用boost条件变量timed_wait

时间:2014-07-10 17:07:27

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

我想实现以下案例:

  • 一个连续运行的工作线程,除非通过调用boost :: thread :: interrupt
  • 中断
  • 线程必须在每个块结束时暂停100 ms,但如果另一个线程通知则必须立即唤醒并继续

    WorkerThread()
    {
        while(true)
       {
          ...
          ...
          ... //done with a block of work
    
          //Pause for 100 ms unless notified by another 
         //thread to wake up and continue immediately
      }
    }
    

问题:我可以通过以下方式使用boost :: condition_variable :: timed_wait来使以下方案有效吗?

boost::condition_variable cond;

WorkerThread()
{
    while(true)
    {
       ...
       ...
       ... //done with a block of work


       boost::mutex mut;
       boost::unique_lock<boost::mutex> lock(mut); // this lock will always be 
                                                   //acquired  since no one else 
                                                   //locks *mut*
       cond.timed_wait( lock, boost::posix_time::milliseconds(100) );
    }
}

OtherThread()
{
   //need to make the worker thread immediately wake up
   cond.notify_one();
}

这会有用吗?如果没有,我如何实现上述方案?

0 个答案:

没有答案