ThreadPool的worker函数

threadpool的worker函数,worker函数是在一个单独的线程中执行,是该线程中主要的程序代码段。

void ThreadPool::worker(WorkThread *wt)
{
  _lock.Lock();
  ldout(cct,10) << "worker start" << dendl;

  std::stringstream ss;
  ss << name << " thread " << (void*)pthread_self();
  heartbeat_handle_d *hb = cct->get_heartbeat_map()->add_worker(ss.str());
//该线程的主循环体
  while (!_stop) {

    // manage dynamic thread pool
    //回收_old_threads队列中的废弃的线程
    join_old_threads();
    //将多出的线程从_threads队列中移到_old_threads队列中去。
    if (_threads.size() > _num_threads) {
      ldout(cct,1) << " worker shutting down; too many threads (" << _threads.size() << " > " << _num_threads << ")" << dendl;
      _threads.erase(wt);
      _old_threads.push_back(wt);
      break;
    }
//work_queues是消息队列的列表,其中保存着不同类型的消息队列
    if (!_pause && !work_queues.empty()) {
      WorkQueue_* wq;
      int tries = work_queues.size();
      bool did = false;
      //从work_queues中顺序的获取消息队列,然后取出该消息队列中的消息(item)
      while (tries--) {
    last_work_queue++;
    last_work_queue %= work_queues.size();
    wq = work_queues[last_work_queue];

    void *item = wq->_void_dequeue();
    if (item) {
    //记录当前正在处理的线程数
      processing++;
      ldout(cct,12) << "worker wq " << wq->name << " start processing " << item
            << " (" << processing << " active)" << dendl;
      TPHandle tp_handle(cct, hb, wq->timeout_interval, wq->suicide_interval);
      tp_handle.reset_tp_timeout();
      _lock.Unlock();
      //使用的消息队列的_void_process()方法来处理,该队列中的消息(上文去取出的消息item)
      wq->_void_process(item, tp_handle);
      _lock.Lock();
      //做消息处理后的相关工作
      wq->_void_process_finish(item);
      processing--;
      ldout(cct,15) << "worker wq " << wq->name << " done processing " << item
            << " (" << processing << " active)" << dendl;
      if (_pause || _draining)
        _wait_cond.Signal();
      did = true;
      break;
    }
      }
      if (did)
    continue;
    }

    ldout(cct,20) << "worker waiting" << dendl;
    cct->get_heartbeat_map()->reset_timeout(
      hb,
      cct->_conf->threadpool_default_timeout,
      0);
    _cond.WaitInterval(cct, _lock,
      utime_t(
    cct->_conf->threadpool_empty_queue_max_wait, 0));
  }
  ldout(cct,1) << "worker finish" << dendl;

  cct->get_heartbeat_map()->remove_worker(hb);

  _lock.Unlock();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值