基于C++11的threadpool線程池(簡(jiǎn)潔且可以帶任意多的參數(shù))
C++11 加入了線程庫(kù),從此告別了標(biāo)準(zhǔn)庫(kù)不支持并發(fā)的歷史。然而 c++ 對(duì)于多線程的支持還是比較低級(jí),稍微高級(jí)一點(diǎn)的用法都需要自己去實(shí)現(xiàn),譬如線程池、信號(hào)量等。線程池(thread pool)這個(gè)東西,在面試上多次被問(wèn)到,一般的回答都是:“管理一個(gè)任務(wù)隊(duì)列,一個(gè)線程隊(duì)列,然后每次取一個(gè)任務(wù)分配給一個(gè)線程去做,循環(huán)往復(fù)?!?貌似沒(méi)有問(wèn)題吧。但是寫(xiě)起程序來(lái)的時(shí)候就出問(wèn)題了。
廢話不多說(shuō),先上實(shí)現(xiàn),然后再啰嗦。(dont talk, show me ur code !)
代碼實(shí)現(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ù)或拉姆達(dá)表達(dá)式的匿名函數(shù)執(zhí)行,可以獲取執(zhí)行返回值
//不支持類成員函數(shù), 支持類靜態(tài)成員函數(shù)或全局函數(shù),Opteron()函數(shù)等
class threadpool
{
using Task = std::function<void()>;
// 線程池
std::vector<std::thread> pool;
// 任務(wù)隊(duì)列
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;
{ // 獲取一個(gè)待執(zhí)行的 task
std::unique_lock<std::mutex> lock{ this->m_lock };// unique_lock 相比 lock_guard 的好處是:可以隨時(shí) 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()); // 取一個(gè) 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é)束, 前提:線程一定會(huì)執(zhí)行完
}
}
public:
// 提交一個(gè)任務(wù)
// 調(diào)用.get()獲取返回值會(huì)等待任務(wù)執(zhí)行完,獲取返回值
// 有兩種方法可以實(shí)現(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ù)到隊(duì)列
std::lock_guard<std::mutex> lock{ m_lock };//對(duì)當(dāng)前塊的語(yǔ)句加鎖 lock_guard 是 mutex 的 stack 封裝類,構(gòu)造的時(shí)候 lock(),析構(gòu)的時(shí)候 unlock()
tasks.emplace(
[task]()
{ // push(Task{...})
(*task)();
}
);
}
cv_task.notify_one(); // 喚醒一個(gè)線程執(zhí)行
return future;
}
//空閑線程數(shù)量
int idlCount() { return idlThrNum; }
};
}
#endif
代碼不多吧,上百行代碼就完成了 線程池, 并且, 看看 commit, 哈, 不是固定參數(shù)的, 無(wú)參數(shù)數(shù)量限制! 這得益于可變參數(shù)模板.
怎么使用?
看下面代碼(展開(kāi)查看)
#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提示錯(cuò)誤,但可以編譯運(yùn)行
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()獲取返回值會(huì)等待線程執(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()獲取返回值會(huì)等待線程執(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;
}
為了避嫌,先進(jìn)行一下版權(quán)說(shuō)明:代碼是 me “寫(xiě)”的,但是思路來(lái)自 Internet, 特別是這個(gè)線程池實(shí)現(xiàn)(基本 copy 了這個(gè)實(shí)現(xiàn),加上這位同學(xué)的實(shí)現(xiàn)和解釋,好東西值得 copy ! 然后綜合更改了下,更加簡(jiǎn)潔)。
實(shí)現(xiàn)原理
接著前面的廢話說(shuō)?!肮芾硪粋€(gè)任務(wù)隊(duì)列,一個(gè)線程隊(duì)列,然后每次取一個(gè)任務(wù)分配給一個(gè)線程去做,循環(huán)往復(fù)?!?這個(gè)思路有神馬問(wèn)題?線程池一般要復(fù)用線程,所以如果是取一個(gè) task 分配給某一個(gè) thread,執(zhí)行完之后再重新分配,在語(yǔ)言層面基本都是不支持的:一般語(yǔ)言的 thread 都是執(zhí)行一個(gè)固定的 task 函數(shù),執(zhí)行完畢線程也就結(jié)束了(至少 c++ 是這樣)。so 要如何實(shí)現(xiàn) task 和 thread 的分配呢?
讓每一個(gè) thread 都去執(zhí)行調(diào)度函數(shù):循環(huán)獲取一個(gè) task,然后執(zhí)行之。
idea 是不是很贊!保證了 thread 函數(shù)的唯一性,而且復(fù)用線程執(zhí)行 task 。
即使理解了 idea,代碼還是需要詳細(xì)解釋一下的。
1、一個(gè)線程 pool,一個(gè)任務(wù)隊(duì)列 queue ,應(yīng)該沒(méi)有意見(jiàn);
2、任務(wù)隊(duì)列是典型的生產(chǎn)者-消費(fèi)者模型,本模型至少需要兩個(gè)工具:一個(gè) mutex + 一個(gè)條件變量,或是一個(gè) mutex + 一個(gè)信號(hào)量。mutex 實(shí)際上就是鎖,保證任務(wù)的添加和移除(獲取)的互斥性,一個(gè)條件變量是保證獲取 task 的同步性:一個(gè) empty 的隊(duì)列,線程應(yīng)該等待(阻塞);
3、atomic<bool> 本身是原子類型,從名字上就懂:它們的操作 load()/store() 是原子操作,所以不需要再加 mutex。
c++語(yǔ)言細(xì)節(jié)
即使懂原理也不代表能寫(xiě)出程序,上面用了眾多c++11的“奇技淫巧”,下面簡(jiǎn)單描述之。
- using Task = function<void()> 是類型別名,簡(jiǎn)化了 typedef 的用法。function<void()> 可以認(rèn)為是一個(gè)函數(shù)類型,接受任意原型是 void() 的函數(shù),或是函數(shù)對(duì)象,或是匿名函數(shù)。void() 意思是不帶參數(shù),沒(méi)有返回值。
- pool.emplace_back([this]{...}) 和 pool.push_back([this]{...}) 功能一樣,只不過(guò)前者性能會(huì)更好;
- pool.emplace_back([this]{...}) 是構(gòu)造了一個(gè)線程對(duì)象,執(zhí)行函數(shù)是拉姆達(dá)匿名函數(shù) ;
- 所有對(duì)象的初始化方式均采用了 {},而不再使用 () 方式,因?yàn)轱L(fēng)格不夠一致且容易出錯(cuò);
- 匿名函數(shù): [this]{...} 不多說(shuō)。[] 是捕捉器,this 是引用域外的變量 this指針, 內(nèi)部使用死循環(huán), 由cv_task.wait(lock,[this]{...}) 來(lái)阻塞線程;
- delctype(expr) 用來(lái)推斷 expr 的類型,和 auto 是類似的,相當(dāng)于類型占位符,占據(jù)一個(gè)類型的位置;auto f(A a, B b) -> decltype(a+b) 是一種用法,不能寫(xiě)作 decltype(a+b) f(A a, B b),為啥?! c++ 就是這么規(guī)定的!
- commit 方法是不是略奇葩!可以帶任意多的參數(shù),第一個(gè)參數(shù)是 f,后面依次是函數(shù) f 的參數(shù)!(注意:參數(shù)要傳struct/class的話,建議用pointer,小心變量的作用域) 可變參數(shù)模板是 c++11 的一大亮點(diǎn),夠亮!至于為什么是 Arg... 和 arg... ,因?yàn)橐?guī)定就是這么用的!
- commit 直接使用只能調(diào)用stdcall函數(shù),但有兩種方法可以實(shí)現(xiàn)調(diào)用類成員,一種是使用 bind: .commit(std::bind(&Dog::sayHello, &dog)); 一種是用 mem_fn: .commit(std::mem_fn(&Dog::sayHello), &dog);
- make_shared 用來(lái)構(gòu)造 shared_ptr 智能指針。用法大體是 shared_ptr<int> p = make_shared<int>(4) 然后 *p == 4 。智能指針的好處就是, 自動(dòng) delete !
- bind 函數(shù),接受函數(shù) f 和部分參數(shù),返回currying后的匿名函數(shù),譬如 bind(add, 4) 可以實(shí)現(xiàn)類似 add4 的函數(shù)!
- forward() 函數(shù),類似于 move() 函數(shù),后者是將參數(shù)右值化,前者是... 腫么說(shuō)呢?大概意思就是:不改變最初傳入的類型的引用類型(左值還是左值,右值還是右值);
- packaged_task 就是任務(wù)函數(shù)的封裝類,通過(guò) get_future 獲取 future , 然后通過(guò) future 可以獲取函數(shù)的返回值(future.get());packaged_task 本身可以像函數(shù)一樣調(diào)用 () ;
- queue 是隊(duì)列類, front() 獲取頭部元素, pop() 移除頭部元素;back() 獲取尾部元素,push() 尾部添加元素;
- lock_guard 是 mutex 的 stack 封裝類,構(gòu)造的時(shí)候 lock(),析構(gòu)的時(shí)候 unlock(),是 c++ RAII 的 idea;
- condition_variable cv; 條件變量, 需要配合 unique_lock 使用;unique_lock 相比 lock_guard 的好處是:可以隨時(shí) unlock() 和 lock()。 cv.wait() 之前需要持有 mutex,wait 本身會(huì) unlock() mutex,如果條件滿足則會(huì)重新持有 mutex。
- 最后線程池析構(gòu)的時(shí)候,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]
相關(guān)文章
C語(yǔ)言設(shè)計(jì)實(shí)現(xiàn)掃描器的自動(dòng)機(jī)的示例詳解
這篇文章主要為大家詳細(xì)介紹了如何利用C語(yǔ)言設(shè)計(jì)實(shí)現(xiàn)掃描器的自動(dòng)機(jī),可識(shí)別的單詞包括:關(guān)鍵字、界符、標(biāo)識(shí)符和常整型數(shù),感興趣的小伙伴可以了解一下2022-12-12
一文詳解Qt如何讀取和寫(xiě)入配置文件的數(shù)據(jù)
這篇文章主要為大家詳細(xì)介紹了在Qt中如何實(shí)現(xiàn)讀取和寫(xiě)入配置文件的數(shù)據(jù),文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,感興趣的小伙伴可以了解一下2023-03-03
C++ 多態(tài)性虛函數(shù)和動(dòng)態(tài)綁定學(xué)習(xí)筆記
這篇文章主要為大家介紹了C++ 多態(tài)性虛函數(shù)和動(dòng)態(tài)綁定學(xué)習(xí)筆記,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10
C++/Php/Python 語(yǔ)言執(zhí)行shell命令的方法(推薦)
下面小編就為大家?guī)?lái)一篇C++/Php/Python 語(yǔ)言執(zhí)行shell命令的方法(推薦)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-03-03
C語(yǔ)言數(shù)組實(shí)現(xiàn)公交車管理系統(tǒng)
這篇文章主要介紹了C語(yǔ)言數(shù)組實(shí)現(xiàn)公交車管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-12-12

