基于C++11的threadpool線程池(簡潔且可以帶任意多的參數(shù))
C++11 加入了線程庫,從此告別了標準庫不支持并發(fā)的歷史。然而 c++ 對于多線程的支持還是比較低級,稍微高級一點的用法都需要自己去實現(xiàn),譬如線程池、信號量等。線程池(thread pool)這個東西,在面試上多次被問到,一般的回答都是:“管理一個任務(wù)隊列,一個線程隊列,然后每次取一個任務(wù)分配給一個線程去做,循環(huán)往復(fù)?!?貌似沒有問題吧。但是寫起程序來的時候就出問題了。
廢話不多說,先上實現(xiàn),然后再啰嗦。(dont talk, show me ur code !)
代碼實現(xiàn)
#pragma once
#ifndef THREAD_POOL_H
#define THREAD_POOL_H
#include <vector>
#include <queue>
#include <thread>
#include <atomic>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>
namespace std
{
#define MAX_THREAD_NUM 256
//線程池,可以提交變參函數(shù)或拉姆達表達式的匿名函數(shù)執(zhí)行,可以獲取執(zhí)行返回值
//不支持類成員函數(shù), 支持類靜態(tài)成員函數(shù)或全局函數(shù),Opteron()函數(shù)等
class threadpool
{
using Task = std::function<void()>;
// 線程池
std::vector<std::thread> pool;
// 任務(wù)隊列
std::queue<Task> tasks;
// 同步
std::mutex m_lock;
// 條件阻塞
std::condition_variable cv_task;
// 是否關(guān)閉提交
std::atomic<bool> stoped;
//空閑線程數(shù)量
std::atomic<int> idlThrNum;
public:
inline threadpool(unsigned short size = 4) :stoped{ false }
{
idlThrNum = size < 1 ? 1 : size;
for (size = 0; size < idlThrNum; ++size)
{ //初始化線程數(shù)量
pool.emplace_back(
[this]
{ // 工作線程函數(shù)
while(!this->stoped)
{
std::function<void()> task;
{ // 獲取一個待執(zhí)行的 task
std::unique_lock<std::mutex> lock{ this->m_lock };// unique_lock 相比 lock_guard 的好處是:可以隨時 unlock() 和 lock()
this->cv_task.wait(lock,
[this] {
return this->stoped.load() || !this->tasks.empty();
}
); // wait 直到有 task
if (this->stoped && this->tasks.empty())
return;
task = std::move(this->tasks.front()); // 取一個 task
this->tasks.pop();
}
idlThrNum--;
task();
idlThrNum++;
}
}
);
}
}
inline ~threadpool()
{
stoped.store(true);
cv_task.notify_all(); // 喚醒所有線程執(zhí)行
for (std::thread& thread : pool) {
//thread.detach(); // 讓線程“自生自滅”
if(thread.joinable())
thread.join(); // 等待任務(wù)結(jié)束, 前提:線程一定會執(zhí)行完
}
}
public:
// 提交一個任務(wù)
// 調(diào)用.get()獲取返回值會等待任務(wù)執(zhí)行完,獲取返回值
// 有兩種方法可以實現(xiàn)調(diào)用類成員,
// 一種是使用 bind: .commit(std::bind(&Dog::sayHello, &dog));
// 一種是用 mem_fn: .commit(std::mem_fn(&Dog::sayHello), &dog)
template<class F, class... Args>
auto commit(F&& f, Args&&... args) ->std::future<decltype(f(args...))>
{
if (stoped.load()) // stop == true ??
throw std::runtime_error("commit on ThreadPool is stopped.");
using RetType = decltype(f(args...)); // typename std::result_of<F(Args...)>::type, 函數(shù) f 的返回值類型
auto task = std::make_shared<std::packaged_task<RetType()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
); // wtf !
std::future<RetType> future = task->get_future();
{ // 添加任務(wù)到隊列
std::lock_guard<std::mutex> lock{ m_lock };//對當前塊的語句加鎖 lock_guard 是 mutex 的 stack 封裝類,構(gòu)造的時候 lock(),析構(gòu)的時候 unlock()
tasks.emplace(
[task]()
{ // push(Task{...})
(*task)();
}
);
}
cv_task.notify_one(); // 喚醒一個線程執(zhí)行
return future;
}
//空閑線程數(shù)量
int idlCount() { return idlThrNum; }
};
}
#endif
代碼不多吧,上百行代碼就完成了 線程池, 并且, 看看 commit, 哈, 不是固定參數(shù)的, 無參數(shù)數(shù)量限制! 這得益于可變參數(shù)模板.
怎么使用?
看下面代碼(展開查看)
#include "threadpool.h"
#include <iostream>
void fun1(int slp)
{
printf(" hello, fun1 ! %d\n" ,std::this_thread::get_id());
if (slp>0) {
printf(" ======= fun1 sleep %d ========= %d\n",slp, std::this_thread::get_id());
std::this_thread::sleep_for(std::chrono::milliseconds(slp));
}
}
struct gfun {
int operator()(int n) {
printf("%d hello, gfun ! %d\n" ,n, std::this_thread::get_id() );
return 42;
}
};
class A {
public:
static int Afun(int n = 0) { //函數(shù)必須是 static 的才能直接使用線程池
std::cout << n << " hello, Afun ! " << std::this_thread::get_id() << std::endl;
return n;
}
static std::string Bfun(int n, std::string str, char c) {
std::cout << n << " hello, Bfun ! "<< str.c_str() <<" " << (int)c <<" " << std::this_thread::get_id() << std::endl;
return str;
}
};
int main()
try {
std::threadpool executor{ 50 };
A a;
std::future<void> ff = executor.commit(fun1,0);
std::future<int> fg = executor.commit(gfun{},0);
std::future<int> gg = executor.commit(a.Afun, 9999); //IDE提示錯誤,但可以編譯運行
std::future<std::string> gh = executor.commit(A::Bfun, 9998,"mult args", 123);
std::future<std::string> fh = executor.commit([]()->std::string { std::cout << "hello, fh ! " << std::this_thread::get_id() << std::endl; return "hello,fh ret !"; });
std::cout << " ======= sleep ========= " << std::this_thread::get_id() << std::endl;
std::this_thread::sleep_for(std::chrono::microseconds(900));
for (int i = 0; i < 50; i++) {
executor.commit(fun1,i*100 );
}
std::cout << " ======= commit all ========= " << std::this_thread::get_id()<< " idlsize="<<executor.idlCount() << std::endl;
std::cout << " ======= sleep ========= " << std::this_thread::get_id() << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(3));
ff.get(); //調(diào)用.get()獲取返回值會等待線程執(zhí)行完,獲取返回值
std::cout << fg.get() << " " << fh.get().c_str()<< " " << std::this_thread::get_id() << std::endl;
std::cout << " ======= sleep ========= " << std::this_thread::get_id() << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(3));
std::cout << " ======= fun1,55 ========= " << std::this_thread::get_id() << std::endl;
executor.commit(fun1,55).get(); //調(diào)用.get()獲取返回值會等待線程執(zhí)行完
std::cout << "end... " << std::this_thread::get_id() << std::endl;
std::threadpool pool(4);
std::vector< std::future<int> > results;
for (int i = 0; i < 8; ++i) {
results.emplace_back(
pool.commit([i] {
std::cout << "hello " << i << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "world " << i << std::endl;
return i*i;
})
);
}
std::cout << " ======= commit all2 ========= " << std::this_thread::get_id() << std::endl;
for (auto && result : results)
std::cout << result.get() << ' ';
std::cout << std::endl;
return 0;
}
catch (std::exception& e) {
std::cout << "some unhappy happened... " << std::this_thread::get_id() << e.what() << std::endl;
}
為了避嫌,先進行一下版權(quán)說明:代碼是 me “寫”的,但是思路來自 Internet, 特別是這個線程池實現(xiàn)(基本 copy 了這個實現(xiàn),加上這位同學的實現(xiàn)和解釋,好東西值得 copy ! 然后綜合更改了下,更加簡潔)。
實現(xiàn)原理
接著前面的廢話說?!肮芾硪粋€任務(wù)隊列,一個線程隊列,然后每次取一個任務(wù)分配給一個線程去做,循環(huán)往復(fù)。” 這個思路有神馬問題?線程池一般要復(fù)用線程,所以如果是取一個 task 分配給某一個 thread,執(zhí)行完之后再重新分配,在語言層面基本都是不支持的:一般語言的 thread 都是執(zhí)行一個固定的 task 函數(shù),執(zhí)行完畢線程也就結(jié)束了(至少 c++ 是這樣)。so 要如何實現(xiàn) task 和 thread 的分配呢?
讓每一個 thread 都去執(zhí)行調(diào)度函數(shù):循環(huán)獲取一個 task,然后執(zhí)行之。
idea 是不是很贊!保證了 thread 函數(shù)的唯一性,而且復(fù)用線程執(zhí)行 task 。
即使理解了 idea,代碼還是需要詳細解釋一下的。
1、一個線程 pool,一個任務(wù)隊列 queue ,應(yīng)該沒有意見;
2、任務(wù)隊列是典型的生產(chǎn)者-消費者模型,本模型至少需要兩個工具:一個 mutex + 一個條件變量,或是一個 mutex + 一個信號量。mutex 實際上就是鎖,保證任務(wù)的添加和移除(獲取)的互斥性,一個條件變量是保證獲取 task 的同步性:一個 empty 的隊列,線程應(yīng)該等待(阻塞);
3、atomic<bool> 本身是原子類型,從名字上就懂:它們的操作 load()/store() 是原子操作,所以不需要再加 mutex。
c++語言細節(jié)
即使懂原理也不代表能寫出程序,上面用了眾多c++11的“奇技淫巧”,下面簡單描述之。
- using Task = function<void()> 是類型別名,簡化了 typedef 的用法。function<void()> 可以認為是一個函數(shù)類型,接受任意原型是 void() 的函數(shù),或是函數(shù)對象,或是匿名函數(shù)。void() 意思是不帶參數(shù),沒有返回值。
- pool.emplace_back([this]{...}) 和 pool.push_back([this]{...}) 功能一樣,只不過前者性能會更好;
- pool.emplace_back([this]{...}) 是構(gòu)造了一個線程對象,執(zhí)行函數(shù)是拉姆達匿名函數(shù) ;
- 所有對象的初始化方式均采用了 {},而不再使用 () 方式,因為風格不夠一致且容易出錯;
- 匿名函數(shù): [this]{...} 不多說。[] 是捕捉器,this 是引用域外的變量 this指針, 內(nèi)部使用死循環(huán), 由cv_task.wait(lock,[this]{...}) 來阻塞線程;
- delctype(expr) 用來推斷 expr 的類型,和 auto 是類似的,相當于類型占位符,占據(jù)一個類型的位置;auto f(A a, B b) -> decltype(a+b) 是一種用法,不能寫作 decltype(a+b) f(A a, B b),為啥?! c++ 就是這么規(guī)定的!
- commit 方法是不是略奇葩!可以帶任意多的參數(shù),第一個參數(shù)是 f,后面依次是函數(shù) f 的參數(shù)!(注意:參數(shù)要傳struct/class的話,建議用pointer,小心變量的作用域) 可變參數(shù)模板是 c++11 的一大亮點,夠亮!至于為什么是 Arg... 和 arg... ,因為規(guī)定就是這么用的!
- commit 直接使用只能調(diào)用stdcall函數(shù),但有兩種方法可以實現(xiàn)調(diào)用類成員,一種是使用 bind: .commit(std::bind(&Dog::sayHello, &dog)); 一種是用 mem_fn: .commit(std::mem_fn(&Dog::sayHello), &dog);
- make_shared 用來構(gòu)造 shared_ptr 智能指針。用法大體是 shared_ptr<int> p = make_shared<int>(4) 然后 *p == 4 。智能指針的好處就是, 自動 delete !
- bind 函數(shù),接受函數(shù) f 和部分參數(shù),返回currying后的匿名函數(shù),譬如 bind(add, 4) 可以實現(xiàn)類似 add4 的函數(shù)!
- forward() 函數(shù),類似于 move() 函數(shù),后者是將參數(shù)右值化,前者是... 腫么說呢?大概意思就是:不改變最初傳入的類型的引用類型(左值還是左值,右值還是右值);
- packaged_task 就是任務(wù)函數(shù)的封裝類,通過 get_future 獲取 future , 然后通過 future 可以獲取函數(shù)的返回值(future.get());packaged_task 本身可以像函數(shù)一樣調(diào)用 () ;
- queue 是隊列類, front() 獲取頭部元素, pop() 移除頭部元素;back() 獲取尾部元素,push() 尾部添加元素;
- lock_guard 是 mutex 的 stack 封裝類,構(gòu)造的時候 lock(),析構(gòu)的時候 unlock(),是 c++ RAII 的 idea;
- condition_variable cv; 條件變量, 需要配合 unique_lock 使用;unique_lock 相比 lock_guard 的好處是:可以隨時 unlock() 和 lock()。 cv.wait() 之前需要持有 mutex,wait 本身會 unlock() mutex,如果條件滿足則會重新持有 mutex。
- 最后線程池析構(gòu)的時候,join() 可以等待任務(wù)都執(zhí)行完在結(jié)束,很安全!
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]
上一篇:C++ 獲取進程CPU占用率
欄 目:C語言
本文標題:基于C++11的threadpool線程池(簡潔且可以帶任意多的參數(shù))
本文地址:http://www.jygsgssxh.com/a1/Cyuyan/349.html
您可能感興趣的文章
- 04-02c語言的正則匹配函數(shù) c語言正則表達式函數(shù)庫
- 04-02c語言中對數(shù)函數(shù)的表達式 c語言中對數(shù)怎么表達
- 04-02C語言中怎么打出三角函數(shù) c語言中怎么打出三角函數(shù)的值
- 01-10c語言求1+2+...+n的解決方法
- 01-10求子數(shù)組最大和的解決方法詳解
- 01-10深入理解約瑟夫環(huán)的數(shù)學優(yōu)化方法
- 01-10深入二叉樹兩個結(jié)點的最低共同父結(jié)點的詳解
- 01-10數(shù)據(jù)結(jié)構(gòu)課程設(shè)計- 解析最少換車次數(shù)的問題詳解
- 01-10c語言 跳臺階問題的解決方法
- 01-10如何判斷一個數(shù)是否為2的冪次方?若是,并判斷出來是多少次方


閱讀排行
本欄相關(guān)
- 04-02c語言函數(shù)調(diào)用后清空內(nèi)存 c語言調(diào)用
- 04-02func函數(shù)+在C語言 func函數(shù)在c語言中
- 04-02c語言的正則匹配函數(shù) c語言正則表達
- 04-02c語言用函數(shù)寫分段 用c語言表示分段
- 04-02c語言中對數(shù)函數(shù)的表達式 c語言中對
- 04-02c語言編寫函數(shù)冒泡排序 c語言冒泡排
- 04-02c語言沒有round函數(shù) round c語言
- 04-02c語言分段函數(shù)怎么求 用c語言求分段
- 04-02C語言中怎么打出三角函數(shù) c語言中怎
- 04-02c語言調(diào)用函數(shù)求fibo C語言調(diào)用函數(shù)求
隨機閱讀
- 01-10C#中split用法實例總結(jié)
- 01-10delphi制作wav文件的方法
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 04-02jquery與jsp,用jquery
- 08-05織夢dedecms什么時候用欄目交叉功能?
- 01-10使用C語言求解撲克牌的順子及n個骰子
- 01-11ajax實現(xiàn)頁面的局部加載
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置


