在學muduo庫之前,我只知道一點線程池的概念,但是對於怎麼實現線程池完全不瞭解,最近因爲被分配到了一個實驗室裏項目小組,於是開始學習muduo庫。
在看了幾遍muduo庫中的ThreadPool線程池類的實現之後,感覺對線程池有了一些瞭解,就簡單對muduo庫是如何實現線程池做一些簡單的說明,順便加深一下記憶。
前置知識:
實現思路:
muduo::ThreadPool類的使用
/*********************************************************
* Author : crazy_mad
* Last modified : 2017-04-13 21:19
* Filename : main.cc
* Description : 測試muduo中的ThreadPool線程池
*********************************************************/
#include <muduo/base/ThreadPool.h>
#include <boost/bind.hpp>
#include <iostream>
#include <string>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
using namespace std;
using namespace muduo;
void say_1() {
cout << "this is say_1" << endl;
}
void say_2(std::string line) {
cout << line << endl;
}
int main() {
ThreadPool pool_("crazymad's pool");
pool_.setMaxQueueSize(10); // 設置任務列表容量
pool_.start(2); // 開啓兩個線程
pool_.run(say_1); // 傳入任務
pool_.run(boost::bind(say_2, std::string("hello world")));
pool_.run(boost::bind(say_2, std::string("crazy_mad很帥")));
sleep(1); // ThreadPool沒有等待子線程運行完畢的機制,這裏爲了方便就手動等一秒鐘好了
return 0;
}