在项目中需要实现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.