zoukankan      html  css  js  c++  java
  • 使用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.

  • 相关阅读:
    JS基础_自增和自减
    计算机组成原理
    SyntaxHighlighter
    10个经典的C语言面试基础算法及代码
    知名互联网公司面试题
    计算机网络基础知识(笔试题)
    面试准备之常见上机题目搜罗
    小米2013年校园招聘笔试题-简单并查集
    2014华为上机试题
    C++学习笔记
  • 原文地址:https://www.cnblogs.com/chutianyao/p/2670399.html
Copyright © 2011-2022 走看看