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.

  • 相关阅读:
    spring boot的application配置文件
    C# WinForm 中英文实现, 国际化实现的简单方法
    VS2012 2013 显示查找功能 无法具体定位 解决方法
    C#使用HttpWebRequest 进行请求,提示 基础连接已经关闭: 发送时发生错误。
    VS 默认开发环境如何更改
    C# winfrom HttpWebRequest 请求获取html网页信息和提交信息
    C# 定时器 Timers.Timer Forms.Timer
    HTTP 错误 500.21
    配置iis时,浏览项目提示 无法识别的属性“targetFramework”。请注意属性名称区分大小写。
    asp xml对象转换为string
  • 原文地址:https://www.cnblogs.com/chutianyao/p/2670399.html
Copyright © 2011-2022 走看看