tanghai 15 лет назад
Родитель
Сommit
5761e57b91
3 измененных файлов с 18 добавлено и 14 удалено
  1. 13 8
      src/thread/thread_pool.cc
  2. 2 2
      src/thread/thread_pool.h
  3. 3 4
      src/thread/thread_pool_test.cc

+ 13 - 8
src/thread/thread_pool.cc

@@ -17,7 +17,7 @@ namespace hainan
 		running = true;
 		for(int i = 0; i < num; ++i)
 		{
-			shared_ptr<thread> t(new thread(bind(&ThreadPool::Loop, ref(this))));
+			shared_ptr<thread> t(new thread(bind(&ThreadPool::Runner, this)));
 			threads.push_back(t);
 			t->detach();
 		}
@@ -37,21 +37,22 @@ namespace hainan
 		}
 	}
 
-	void ThreadPool::Loop()
+	void ThreadPool::Runner()
 	{
 		VLOG(2) << "thread start";
 		bool continued = true;
 		while(continued)
 		{
-			function<void (void)> task(0);
+			function<void (void)> task;
 			{
+				VLOG(2) << "loop lock";
 				mutex::scoped_lock lock(mtx);
-				if(running && tasks.empty())
+				VLOG(2) << "loop lock ok";
+				while(running && tasks.empty())
 				{
 					cond.wait(lock);
-					VLOG(2) << "get cond";
+					VLOG(2) << "cond";
 				}
-
 				if(!tasks.empty())
 				{
 					VLOG(2) << "fetch task";
@@ -59,7 +60,10 @@ namespace hainan
 					tasks.pop_front();
 				}
 				continued = running || !tasks.empty();
-				VLOG(2) << "running = " << running;
+				VLOG(2) << "continued = " << continued
+						<< "running = " << running
+						<< " tasks size = " << tasks.size();
+				VLOG(2) << "loop unlock";
 			}
 
 			if(task)
@@ -85,11 +89,12 @@ namespace hainan
 			}
 			tasks.push_back(task);
 		}
+		VLOG(2) << "push task unlock";
 		cond.notify_one();
 		return true;
 	}
 
-	void ThreadPool::SetNum(int32_t n)
+	void ThreadPool::SetNum(int n)
 	{
 		num = n;
 	}

+ 2 - 2
src/thread/thread_pool.h

@@ -24,7 +24,7 @@ namespace hainan
 		list<shared_ptr<thread> > threads;
 		list<function<void (void)> > tasks;
 
-		void Loop();
+		void Runner();
 
 		ThreadPool(ThreadPool const&);
 		ThreadPool operator=(ThreadPool const&);
@@ -34,7 +34,7 @@ namespace hainan
 		void Start();
 		void Stop();
 		void SetNum(int n);
-		bool PushTask(function<void(void)> task);
+		bool PushTask(function<void (void)> task);
 	};
 }
 #endif  // THREAD_THREAD_POOL_H

+ 3 - 4
src/thread/thread_pool_test.cc

@@ -11,7 +11,7 @@ namespace hainan
 	{
 		void SetUp()
 		{
-			thread_pool.SetNum(2);
+			thread_pool.SetNum(10);
 			thread_pool.Start();
 		}
 		void TearDown()
@@ -34,12 +34,11 @@ namespace hainan
 		vector<int> x(100, 8);
 		vector<int> y(100, 9);
 		vector<int> z(100, 0);
-
 		for(int i = 0; i < 100; ++i)
 		{
 			thread_pool.PushTask(
-				boost::bind(&ThreadPoolTest::Max,
-					boost::ref(*this), x[i], y[i], &z[i]));
+				bind(&ThreadPoolTest::Max,
+					this, x[i], y[i], &z[i]));
 		}
 		thread_pool.Stop();
 		for(int i = 0; i < 100; ++i)