Add worker thread
[trackerpp.git] / src / WorkerThread.cpp
1 #include "WorkerThread.h"
2 #include <iostream>
3 #include "Logger.h"
4
5 using namespace suanzi;
6 using namespace std;
7
8 static const std::string TAG = "WorkerThread";
9
10 WorkerThread::WorkerThread(const std::string& name) 
11 : m_name(name)
12 , m_thread (thread(&WorkerThread::run, this))
13 {
14 }
15
16 WorkerThread::~WorkerThread()
17 {
18 }
19
20 void WorkerThread::run()
21 {
22     LOG_DEBUG(TAG, "start workerThread " + m_name);
23     WorkItemPtr workItem;
24     while(true){
25         unique_lock<mutex> l(m_mutex);
26         if (!m_queue.empty()){
27             workItem = m_queue.front();
28             m_queue.pop();
29             l.unlock();
30             workItem->run();
31             LOG_DEBUG(TAG, " ------ Queue Size: " << m_queue.size());
32         } else {
33             m_cond.wait(l);
34         }
35     }
36     LOG_DEBUG(TAG, "End workerThread " + m_name);
37 }
38
39 void WorkerThread::enqueue(WorkItemPtr item)
40 {
41     unique_lock<mutex> l(m_mutex);
42     m_queue.push(item);
43     m_cond.notify_one();
44 }
45
46 void WorkerThread::enqueue(WorkItem* w)
47 {
48     WorkItemPtr p (w);
49     enqueue(p);
50 }