咳咳。C++11 加入了線程庫,從此告別了標准庫不支持並發的歷史。然而 c++ 對於多線程的支持還是比較低級,稍微高級一點的用法都需要自己去實現,譬如線程池、信號量等。線程池(thread pool)這個東西,在面試上多次被問到,一般的回答都是:“管理一個任務隊列,一個線程隊列,然后每次取一個任務分配給一個線程去做,循環往復。” 貌似沒有問題吧。但是寫起程序來的時候就出問題了。
廢話不多說,先上實現,然后再啰嗦。(dont talk, show me ur code !)
代碼實現
1 #pragma once 2 #ifndef THREAD_POOL_H 3 #define THREAD_POOL_H 4 5 #include <vector> 6 #include <queue> 7 #include <thread> 8 #include <atomic> 9 #include <condition_variable> 10 #include <future> 11 #include <functional> 12 #include <stdexcept> 13 14 namespace std 15 { 16 #define MAX_THREAD_NUM 256 17 18 //線程池,可以提交變參函數或拉姆達表達式的匿名函數執行,可以獲取執行返回值 19 //不支持類成員函數, 支持類靜態成員函數或全局函數,Opteron()函數等 20 class threadpool 21 { 22 using Task = std::function<void()>; 23 // 線程池 24 std::vector<std::thread> pool; 25 // 任務隊列 26 std::queue<Task> tasks; 27 // 同步 28 std::mutex m_lock; 29 // 條件阻塞 30 std::condition_variable cv_task; 31 // 是否關閉提交 32 std::atomic<bool> stoped; 33 //空閑線程數量 34 std::atomic<int> idlThrNum; 35 36 public: 37 inline threadpool(unsigned short size = 4) :stoped{ false } 38 { 39 idlThrNum = size < 1 ? 1 : size; 40 for (size = 0; size < idlThrNum; ++size) 41 { //初始化線程數量 42 pool.emplace_back( 43 [this] 44 { // 工作線程函數 45 while(!this->stoped) 46 { 47 std::function<void()> task; 48 { // 獲取一個待執行的 task 49 std::unique_lock<std::mutex> lock{ this->m_lock };// unique_lock 相比 lock_guard 的好處是:可以隨時 unlock() 和 lock() 50 this->cv_task.wait(lock, 51 [this] { 52 return this->stoped.load() || !this->tasks.empty(); 53 } 54 ); // wait 直到有 task 55 if (this->stoped && this->tasks.empty()) 56 return; 57 task = std::move(this->tasks.front()); // 取一個 task 58 this->tasks.pop(); 59 } 60 idlThrNum--; 61 task(); 62 idlThrNum++; 63 } 64 } 65 ); 66 } 67 } 68 inline ~threadpool() 69 { 70 stoped.store(true); 71 cv_task.notify_all(); // 喚醒所有線程執行 72 for (std::thread& thread : pool) { 73 //thread.detach(); // 讓線程“自生自滅” 74 if(thread.joinable()) 75 thread.join(); // 等待任務結束, 前提:線程一定會執行完 76 } 77 } 78 79 public: 80 // 提交一個任務 81 // 調用.get()獲取返回值會等待任務執行完,獲取返回值 82 // 有兩種方法可以實現調用類成員, 83 // 一種是使用 bind: .commit(std::bind(&Dog::sayHello, &dog)); 84 // 一種是用 mem_fn: .commit(std::mem_fn(&Dog::sayHello), &dog) 85 template<class F, class... Args> 86 auto commit(F&& f, Args&&... args) ->std::future<decltype(f(args...))> 87 { 88 if (stoped.load()) // stop == true ?? 89 throw std::runtime_error("commit on ThreadPool is stopped."); 90 91 using RetType = decltype(f(args...)); // typename std::result_of<F(Args...)>::type, 函數 f 的返回值類型 92 auto task = std::make_shared<std::packaged_task<RetType()> >( 93 std::bind(std::forward<F>(f), std::forward<Args>(args)...) 94 ); // wtf ! 95 std::future<RetType> future = task->get_future(); 96 { // 添加任務到隊列 97 std::lock_guard<std::mutex> lock{ m_lock };//對當前塊的語句加鎖 lock_guard 是 mutex 的 stack 封裝類,構造的時候 lock(),析構的時候 unlock() 98 tasks.emplace( 99 [task]() 100 { // push(Task{...}) 101 (*task)(); 102 } 103 ); 104 } 105 cv_task.notify_one(); // 喚醒一個線程執行 106 107 return future; 108 } 109 110 //空閑線程數量 111 int idlCount() { return idlThrNum; } 112 113 }; 114 115 } 116 117 #endif
代碼不多吧,上百行代碼就完成了 線程池, 並且, 看看 commit, 哈, 不是固定參數的, 無參數數量限制! 這得益於可變參數模板.
怎么使用?
看下面代碼(展開查看)

1 #include "threadpool.h" 2 #include <iostream> 3 4 void fun1(int slp) 5 { 6 printf(" hello, fun1 ! %d\n" ,std::this_thread::get_id()); 7 if (slp>0) { 8 printf(" ======= fun1 sleep %d ========= %d\n",slp, std::this_thread::get_id()); 9 std::this_thread::sleep_for(std::chrono::milliseconds(slp)); 10 } 11 } 12 13 struct gfun { 14 int operator()(int n) { 15 printf("%d hello, gfun ! %d\n" ,n, std::this_thread::get_id() ); 16 return 42; 17 } 18 }; 19 20 class A { 21 public: 22 static int Afun(int n = 0) { //函數必須是 static 的才能直接使用線程池 23 std::cout << n << " hello, Afun ! " << std::this_thread::get_id() << std::endl; 24 return n; 25 } 26 27 static std::string Bfun(int n, std::string str, char c) { 28 std::cout << n << " hello, Bfun ! "<< str.c_str() <<" " << (int)c <<" " << std::this_thread::get_id() << std::endl; 29 return str; 30 } 31 }; 32 33 int main() 34 try { 35 std::threadpool executor{ 50 }; 36 A a; 37 std::future<void> ff = executor.commit(fun1,0); 38 std::future<int> fg = executor.commit(gfun{},0); 39 std::future<int> gg = executor.commit(a.Afun, 9999); //IDE提示錯誤,但可以編譯運行 40 std::future<std::string> gh = executor.commit(A::Bfun, 9998,"mult args", 123); 41 std::future<std::string> fh = executor.commit([]()->std::string { std::cout << "hello, fh ! " << std::this_thread::get_id() << std::endl; return "hello,fh ret !"; }); 42 43 std::cout << " ======= sleep ========= " << std::this_thread::get_id() << std::endl; 44 std::this_thread::sleep_for(std::chrono::microseconds(900)); 45 46 for (int i = 0; i < 50; i++) { 47 executor.commit(fun1,i*100 ); 48 } 49 std::cout << " ======= commit all ========= " << std::this_thread::get_id()<< " idlsize="<<executor.idlCount() << std::endl; 50 51 std::cout << " ======= sleep ========= " << std::this_thread::get_id() << std::endl; 52 std::this_thread::sleep_for(std::chrono::seconds(3)); 53 54 ff.get(); //調用.get()獲取返回值會等待線程執行完,獲取返回值 55 std::cout << fg.get() << " " << fh.get().c_str()<< " " << std::this_thread::get_id() << std::endl; 56 57 std::cout << " ======= sleep ========= " << std::this_thread::get_id() << std::endl; 58 std::this_thread::sleep_for(std::chrono::seconds(3)); 59 60 std::cout << " ======= fun1,55 ========= " << std::this_thread::get_id() << std::endl; 61 executor.commit(fun1,55).get(); //調用.get()獲取返回值會等待線程執行完 62 63 std::cout << "end... " << std::this_thread::get_id() << std::endl; 64 65 66 std::threadpool pool(4); 67 std::vector< std::future<int> > results; 68 69 for (int i = 0; i < 8; ++i) { 70 results.emplace_back( 71 pool.commit([i] { 72 std::cout << "hello " << i << std::endl; 73 std::this_thread::sleep_for(std::chrono::seconds(1)); 74 std::cout << "world " << i << std::endl; 75 return i*i; 76 }) 77 ); 78 } 79 std::cout << " ======= commit all2 ========= " << std::this_thread::get_id() << std::endl; 80 81 for (auto && result : results) 82 std::cout << result.get() << ' '; 83 std::cout << std::endl; 84 return 0; 85 } 86 catch (std::exception& e) { 87 std::cout << "some unhappy happened... " << std::this_thread::get_id() << e.what() << std::endl; 88 }
為了避嫌,先進行一下版權說明:代碼是 me “寫”的,但是思路來自 Internet, 特別是這個線程池實現(基本 copy 了這個實現,加上這位同學的實現和解釋,好東西值得 copy ! 然后綜合更改了下,更加簡潔)。
實現原理
接着前面的廢話說。“管理一個任務隊列,一個線程隊列,然后每次取一個任務分配給一個線程去做,循環往復。” 這個思路有神馬問題?線程池一般要復用線程,所以如果是取一個 task 分配給某一個 thread,執行完之后再重新分配,在語言層面基本都是不支持的:一般語言的 thread 都是執行一個固定的 task 函數,執行完畢線程也就結束了(至少 c++ 是這樣)。so 要如何實現 task 和 thread 的分配呢?
讓每一個 thread 都去執行調度函數:循環獲取一個 task,然后執行之。
idea 是不是很贊!保證了 thread 函數的唯一性,而且復用線程執行 task 。
即使理解了 idea,代碼還是需要詳細解釋一下的。
- 一個線程 pool,一個任務隊列 queue ,應該沒有意見;
- 任務隊列是典型的生產者-消費者模型,本模型至少需要兩個工具:一個 mutex + 一個條件變量,或是一個 mutex + 一個信號量。mutex 實際上就是鎖,保證任務的添加和移除(獲取)的互斥性,一個條件變量是保證獲取 task 的同步性:一個 empty 的隊列,線程應該等待(阻塞);
- atomic<bool> 本身是原子類型,從名字上就懂:它們的操作 load()/store() 是原子操作,所以不需要再加 mutex。
c++語言細節
即使懂原理也不代表能寫出程序,上面用了眾多c++11的“奇技淫巧”,下面簡單描述之。
- using Task = function<void()> 是類型別名,簡化了 typedef 的用法。function<void()> 可以認為是一個函數類型,接受任意原型是 void() 的函數,或是函數對象,或是匿名函數。void() 意思是不帶參數,沒有返回值。
- pool.emplace_back([this]{...}) 和 pool.push_back([this]{...}) 功能一樣,只不過前者性能會更好;
- pool.emplace_back([this]{...}) 是構造了一個線程對象,執行函數是拉姆達匿名函數 ;
- 所有對象的初始化方式均采用了 {},而不再使用 () 方式,因為風格不夠一致且容易出錯;
- 匿名函數: [this]{...} 不多說。[] 是捕捉器,this 是引用域外的變量 this指針, 內部使用死循環, 由cv_task.wait(lock,[this]{...}) 來阻塞線程;
- delctype(expr) 用來推斷 expr 的類型,和 auto 是類似的,相當於類型占位符,占據一個類型的位置;auto f(A a, B b) -> decltype(a+b) 是一種用法,不能寫作 decltype(a+b) f(A a, B b),為啥?! c++ 就是這么規定的!
- commit 方法是不是略奇葩!可以帶任意多的參數,第一個參數是 f,后面依次是函數 f 的參數!(注意:參數要傳struct/class的話,建議用pointer,小心變量的作用域) 可變參數模板是 c++11 的一大亮點,夠亮!至於為什么是 Arg... 和 arg... ,因為規定就是這么用的!
- commit 直接使用只能調用stdcall函數,但有兩種方法可以實現調用類成員,一種是使用 bind: .commit(std::bind(&Dog::sayHello, &dog)); 一種是用 mem_fn: .commit(std::mem_fn(&Dog::sayHello), &dog);
- make_shared 用來構造 shared_ptr 智能指針。用法大體是 shared_ptr<int> p = make_shared<int>(4) 然后 *p == 4 。智能指針的好處就是, 自動 delete !
- bind 函數,接受函數 f 和部分參數,返回currying后的匿名函數,譬如 bind(add, 4) 可以實現類似 add4 的函數!
- forward() 函數,類似於 move() 函數,后者是將參數右值化,前者是... 腫么說呢?大概意思就是:不改變最初傳入的類型的引用類型(左值還是左值,右值還是右值);
- packaged_task 就是任務函數的封裝類,通過 get_future 獲取 future , 然后通過 future 可以獲取函數的返回值(future.get());packaged_task 本身可以像函數一樣調用 () ;
- queue 是隊列類, front() 獲取頭部元素, pop() 移除頭部元素;back() 獲取尾部元素,push() 尾部添加元素;
- lock_guard 是 mutex 的 stack 封裝類,構造的時候 lock(),析構的時候 unlock(),是 c++ RAII 的 idea;
- condition_variable cv; 條件變量, 需要配合 unique_lock 使用;unique_lock 相比 lock_guard 的好處是:可以隨時 unlock() 和 lock()。 cv.wait() 之前需要持有 mutex,wait 本身會 unlock() mutex,如果條件滿足則會重新持有 mutex。
- 最后線程池析構的時候,join() 可以等待任務都執行完在結束,很安全!
Git
代碼保存在git,這里可以獲取最新代碼: https://github.com/lzpong/threadpool
[copy right from url: http://blog.csdn.net/zdarks/article/details/46994607, https://github.com/progschj/ThreadPool/blob/master/ThreadPool.h]