咳咳。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 }
爲了避嫌,先進行一下版權說明:代碼是 me 「寫」的,可是思路來自 Internet, 特別是這個線程池實現(基本 copy 了這個實現,加上這位同窗的實現和解釋,好東西值得 copy ! 而後綜合更改了下,更加簡潔)。面試
接着前面的廢話說。「管理一個任務隊列,一個線程隊列,而後每次取一個任務分配給一個線程去作,循環往復。」 這個思路有神馬問題?線程池通常要複用線程,因此若是是取一個 task 分配給某一個 thread,執行完以後再從新分配,在語言層面基本都是不支持的:通常語言的 thread 都是執行一個固定的 task 函數,執行完畢線程也就結束了(至少 c++ 是這樣)。so 要如何實現 task 和 thread 的分配呢?安全
讓每個 thread 都去執行調度函數:循環獲取一個 task,而後執行之。多線程
idea 是否是很贊!保證了 thread 函數的惟一性,並且複用線程執行 task 。併發
即便理解了 idea,代碼仍是須要詳細解釋一下的。app
即便懂原理也不表明能寫出程序,上面用了衆多c++11的「奇技淫巧」,下面簡單描述之。ide
代碼保存在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]