Explorar o código

add threadpool class

tanghai %!s(int64=15) %!d(string=hai) anos
pai
achega
eeeb1b92b1
Modificáronse 3 ficheiros con 105 adicións e 19 borrados
  1. 22 19
      src/experimental/boost_function_test.cc
  2. 55 0
      src/thread/thread_pool.cc
  3. 28 0
      src/thread/thread_pool.h

+ 22 - 19
src/experimental/boost_function_test.cc

@@ -7,29 +7,32 @@
 #include <gflags/gflags.h>
 #include <gflags/gflags.h>
 #include <glog/logging.h>
 #include <glog/logging.h>
 
 
-class BoostTest: public testing::Test
+namespace hainan
 {
 {
-	void SetUp()
+	class BoostTest: public testing::Test
 	{
 	{
-		a = 6;
-	}
-protected:
-	int a;
-	boost::function<int (int)> func;
-public:
-	int Max(int a, int b)
+		void SetUp()
+		{
+			a = 6;
+		}
+	protected:
+		int a;
+		boost::function<int(int)> func;
+	public:
+		int Max(int a, int b)
+		{
+			LOG(INFO) << a << " " << b;
+			return a > b? a : b;
+		}
+	};
+
+	TEST_F(BoostTest, Test1)
 	{
 	{
-		LOG(INFO) << a << " " << b;
-		return a > b? a : b;
+		int x = 5;
+		func = boost::bind(&BoostTest::Max, boost::ref(*this), _1, x);
+		int b = func(a);
+		LOG(INFO) << b;
 	}
 	}
-};
-
-TEST_F(BoostTest, Test1)
-{
-	int x = 5;
-	func = boost::bind(&BoostTest::Max, boost::ref(*this), _1, x);
-	int b = func(a);
-	LOG(INFO) << b;
 }
 }
 
 
 int main(int argc, char* argv[])
 int main(int argc, char* argv[])

+ 55 - 0
src/thread/thread_pool.cc

@@ -0,0 +1,55 @@
+#include "thread/thread_pool.h"
+
+namespace hainan
+{
+	ThreadPool::ThreadPool(int32_t n):
+			num(n), running(false)
+	{
+	}
+
+	void ThreadPool::Start()
+	{
+		for(int i = 0; i < num; ++i)
+		{
+			boost::thread t(boost::function(&ThreadPool::Loop, boost::ref(this)));
+			threads.push_back(t);
+			t.detach();
+		}
+		running = true;
+	}
+
+	void ThreadPool::Stop()
+	{
+		running = false;
+		cond.notify_all();
+	}
+
+	void ThreadPool::Loop()
+	{
+		while(running)
+		{
+			mutex.lock();
+			while(tasks.empty())
+			{
+				cond.wait(mutex);
+			}
+			boost::function& t = tasks.front();
+			tasks.pop_front();
+			cond.notify_one();
+			mutex.unlock();
+			t();
+		}
+	}
+
+	bool ThreadPool::PushTask(boost::function<void(void)> task)
+	{
+		boost::mutex::scoped_lock(&mutex);
+		if(!running)
+		{
+			return false;
+		}
+		tasks.push_back(task);
+		cond.notify_one();
+		return true;
+	}
+}

+ 28 - 0
src/thread/thread_pool.h

@@ -0,0 +1,28 @@
+#include <boost/thread.hpp>
+#include <boost/function.hpp>
+#include <boost/bind.hpp>
+
+namespace hainan
+{
+	class ThreadPool
+	{
+	private:
+		int32_t num;
+		volatile bool running;
+		boost::mutex mutex;
+		boost::condition_variable cond;
+		std::vector<boost::thread> threads;
+		std::list<boost::function<void(void)>> tasks;
+
+		void Loop();
+
+		ThreadPool(ThreadPool const&);
+		ThreadPool operator=(ThreadPool const&);
+	public:
+		ThreadPool();
+		~ThreadPool();
+		void Start();
+		void Stop();
+		bool PushTask(boost::function<void(void)> task);
+	};
+}