基於C++11的線程池(threadpool),簡潔且能夠帶任意多的參數

咳咳。C++11 加入了線程庫,今後告別了標準庫不支持併發的歷史。然而 c++ 對於多線程的支持仍是比較低級,稍微高級一點的用法都須要本身去實現,譬如線程池、信號量等。線程池(thread pool)這個東西,在面試上屢次被問到,通常的回答都是:「管理一個任務隊列,一個線程隊列,而後每次取一個任務分配給一個線程去作,循環往復。」 貌似沒有問題吧。可是寫起程序來的時候就出問題了。ios

廢話很少說,先上實現,而後再囉嗦。(dont talk, show me ur code !)c++

代碼實現

  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,  哈,  不是固定參數的, 無參數數量限制!  這得益於可變參數模板.git

怎麼使用?

 看下面代碼(展開查看)github

 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 }
View Code

 

爲了避嫌,先進行一下版權說明:代碼是 me 「寫」的,可是思路來自 Internet, 特別是這個線程池實現(基本 copy 了這個實現,加上這位同窗的實現和解釋,好東西值得 copy ! 而後綜合更改了下,更加簡潔)。面試

實現原理

接着前面的廢話說。「管理一個任務隊列,一個線程隊列,而後每次取一個任務分配給一個線程去作,循環往復。」 這個思路有神馬問題?線程池通常要複用線程,因此若是是取一個 task 分配給某一個 thread,執行完以後再從新分配,在語言層面基本都是不支持的:通常語言的 thread 都是執行一個固定的 task 函數,執行完畢線程也就結束了(至少 c++ 是這樣)。so 要如何實現 task 和 thread 的分配呢?安全

讓每個 thread 都去執行調度函數:循環獲取一個 task,而後執行之。多線程

idea 是否是很贊!保證了 thread 函數的惟一性,並且複用線程執行 task 。併發

即便理解了 idea,代碼仍是須要詳細解釋一下的。app

  1. 一個線程 pool,一個任務隊列 queue ,應該沒有意見;
  2. 任務隊列是典型的生產者-消費者模型,本模型至少須要兩個工具:一個 mutex + 一個條件變量,或是一個 mutex + 一個信號量。mutex 實際上就是鎖,保證任務的添加和移除(獲取)的互斥性,一個條件變量是保證獲取 task 的同步性:一個 empty 的隊列,線程應該等待(阻塞);
  3. atomic<bool> 自己是原子類型,從名字上就懂:它們的操做 load()/store() 是原子操做,因此不須要再加 mutex。

c++語言細節

即便懂原理也不表明能寫出程序,上面用了衆多c++11的「奇技淫巧」,下面簡單描述之。ide

  1. using Task = function<void()> 是類型別名,簡化了 typedef 的用法。function<void()> 能夠認爲是一個函數類型,接受任意原型是 void() 的函數,或是函數對象,或是匿名函數。void() 意思是不帶參數,沒有返回值。
  2. pool.emplace_back([this]{...}) 和 pool.push_back([this]{...}) 功能同樣,只不過前者性能會更好;
  3. pool.emplace_back([this]{...}) 是構造了一個線程對象,執行函數是拉姆達匿名函數 ;
  4. 全部對象的初始化方式均採用了 {},而再也不使用 () 方式,由於風格不夠一致且容易出錯;
  5. 匿名函數: [this]{...} 很少說。[] 是捕捉器,this 是引用域外的變量 this指針, 內部使用死循環, 由cv_task.wait(lock,[this]{...}) 來阻塞線程;
  6. delctype(expr) 用來推斷 expr 的類型,和 auto 是相似的,至關於類型佔位符,佔據一個類型的位置;auto f(A a, B b) -> decltype(a+b) 是一種用法,不能寫做 decltype(a+b) f(A a, B b),爲啥?! c++ 就是這麼規定的!
  7. commit 方法是否是略奇葩!能夠帶任意多的參數,第一個參數是 f,後面依次是函數 f 的參數!(注意:參數要傳struct/class的話,建議用pointer,當心變量的做用域) 可變參數模板是 c++11 的一大亮點,夠亮!至於爲何是 Arg... 和 arg... ,由於規定就是這麼用的!
  8. commit 直接使用只能調用stdcall函數,但有兩種方法能夠實現調用類成員,一種是使用   bind: .commit(std::bind(&Dog::sayHello, &dog)); 一種是用 mem_fn: .commit(std::mem_fn(&Dog::sayHello), &dog);
  9. make_shared 用來構造 shared_ptr 智能指針。用法大致是 shared_ptr<int> p = make_shared<int>(4) 而後 *p == 4 。智能指針的好處就是, 自動 delete !
  10. bind 函數,接受函數 f 和部分參數,返回currying後的匿名函數,譬如 bind(add, 4) 能夠實現相似 add4 的函數!
  11. forward() 函數,相似於 move() 函數,後者是將參數右值化,前者是... 腫麼說呢?大概意思就是:不改變最初傳入的類型的引用類型(左值仍是左值,右值仍是右值);
  12. packaged_task 就是任務函數的封裝類,經過 get_future 獲取 future , 而後經過 future 能夠獲取函數的返回值(future.get());packaged_task 自己能夠像函數同樣調用 () ;
  13. queue 是隊列類, front() 獲取頭部元素, pop() 移除頭部元素;back() 獲取尾部元素,push() 尾部添加元素;
  14. lock_guard 是 mutex 的 stack 封裝類,構造的時候 lock(),析構的時候 unlock(),是 c++ RAII 的 idea;
  15. condition_variable cv; 條件變量, 須要配合 unique_lock 使用;unique_lock 相比 lock_guard 的好處是:能夠隨時 unlock() 和 lock()。 cv.wait() 以前須要持有 mutex,wait 自己會 unlock() mutex,若是條件知足則會從新持有 mutex。
  16. 最後線程池析構的時候,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]

相關文章
相關標籤/搜索