使用boost::condition实现线程的暂停/启动

在项目中需要实现pause/resume功能,用boost::condition实现大致如下:

1 class Geo
2 {
3     ...
4     bool m_bPauseFlag;
5     boost::condition m_pause_cond;
6     boost::mutex m_pause_mutex;
7     boost::mutex m_pauseflag_mutex;
8 
9 }

实现:

 1 void Geor::pause()
 2 {
 3     LOG_DEBUG("GeoCrawler::pause()!");
 4 
 5     lock l(m_pauseflag_mutex);
 6     m_bPauseFlag = true;
 7 }
 8 
 9 void Geo::resume()
10 {
11     LOG_DEBUG("GeoCrawler::resume()!");
12 
13     lock l(m_pauseflag_mutex);
14     m_bPauseFlag = false;
15     m_pause_cond.notify_all();
16 }
17 
18 void Geo::WorkThread()
19 {
20     while(1)
21     {
22          ...
23          
24         if(m_bPauseFlag == true)
25         {
26             LOG_DEBUG("WAITING...");
27             m_pause_cond.wait(m_pause_mutex);
28             LOG_DEBUG("CONTINUING...");
29         }
30     }
31 }

 

需要注意的是:

m_pause_cond.wait的含义是等待信号并对m_pause_mutex加锁,调用resume()进行unblock之后,线程从wait处继续运行,但是:此时m_pause_mutex并未被解锁,如果在其他地方尝试对m_pause_mutex加锁的话,会一直block的!因此我这里使用了两个mutex,m_pause_mutex是用来传递给m_pause_cond.wait的,m_pauseflag_mutex是用来修改暂停标志的。刚开始我把他们弄混淆了,只是用了一个mutex,最后线程挂住了。

--------------------------------

boost文档说明:

void wait(boost::unique_lock<boost::mutex>& lock

Precondition:
lock is locked by the current thread, and either no other thread is currently waiting on *this, or the execution of the mutex() member function on the lock objects supplied in the calls to wait or timed_wait in all the threads currently waiting on *this would return the same value as lock->mutex() for this call to wait. 

Effects:
Atomically call lock.unlock() and blocks the current thread. The thread will unblock when notified by a call to this->notify_one() or this->notify_all(), or spuriously. When the thread is unblocked (for whatever reason), the lock is reacquired by invoking lock.lock() before the call to wait returns. The lock is also reacquired by invoking lock.lock() if the function exits with an exception. 


Postcondition:
lock is locked by the current thread. 


Throws:
boost::thread_resource_error if an error occurs. boost::thread_interrupted if the wait was interrupted by a call to interrupt() on the boost::thread object associated with the current thread of execution.

 

 

 

转载于:https://www.cnblogs.com/chutianyao/archive/2012/09/04/2670399.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值