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();
}