Add worker thread
[trackerpp.git] / src / WorkerThread.cpp
diff --git a/src/WorkerThread.cpp b/src/WorkerThread.cpp
new file mode 100644 (file)
index 0000000..c31d023
--- /dev/null
@@ -0,0 +1,50 @@
+#include "WorkerThread.h"
+#include <iostream>
+#include "Logger.h"
+
+using namespace suanzi;
+using namespace std;
+
+static const std::string TAG = "WorkerThread";
+
+WorkerThread::WorkerThread(const std::string& name) 
+: m_name(name)
+, m_thread (thread(&WorkerThread::run, this))
+{
+}
+
+WorkerThread::~WorkerThread()
+{
+}
+
+void WorkerThread::run()
+{
+    LOG_DEBUG(TAG, "start workerThread " + m_name);
+    WorkItemPtr workItem;
+    while(true){
+        unique_lock<mutex> l(m_mutex);
+        if (!m_queue.empty()){
+            workItem = m_queue.front();
+            m_queue.pop();
+            l.unlock();
+            workItem->run();
+            LOG_DEBUG(TAG, " ------ Queue Size: " << m_queue.size());
+        } else {
+            m_cond.wait(l);
+        }
+    }
+    LOG_DEBUG(TAG, "End workerThread " + m_name);
+}
+
+void WorkerThread::enqueue(WorkItemPtr item)
+{
+    unique_lock<mutex> l(m_mutex);
+    m_queue.push(item);
+    m_cond.notify_one();
+}
+
+void WorkerThread::enqueue(WorkItem* w)
+{
+    WorkItemPtr p (w);
+    enqueue(p);
+}