這個線程池最初就是為了跟 socket 搭配而寫的。網路上線程池的實作版本多到數不清,我不敢說這份是最優解,但它確實貼近我心裡那個需求模型:任務透過佇列投遞、線程數量能依負載自動擴張與收縮、關閉時能優雅收尾。以下把設計思路與程式碼一併貼出,拋磚引玉,若有更好的做法歡迎一起討論。
Command 是業務載體。刻意只放內建型別,因為它要直接跟 socket 傳輸;cmd_ 存命令字,arg_ 存業務參數,多個參數可用分隔符切開。若日後導入序列化機制,就不需要這種樸素做法了。
ThreadProcess 是實際的業務處理類別,內部的各個方法會由 ThreadPool 的 Process 函數呼叫。ThreadPool 是線程池本體,成員變數一律靜態,Process 為線程進入點。
#define MAX_THREAD_NUM 50 // 該值目前需要設定為初始線程數的整數倍 #define ADD_FACTOR 40 // 該值表示一個線程可以處理的最大任務數 #define THREAD_NUM 10 // 初始線程數
bshutdown_:線程退出旗標。command_:任務佇列。command_cond_ 與 command_mutex_:條件變數與互斥鎖,用來保護佇列並喚醒休眠線程。icurr_thread_num_:目前線程數。thread_id_map_:以 pthread_t 為索引記錄線程狀態,0 為正常、1 為待退出;這個 map 也可以擴充成結構,額外存放 socket 等資訊。方法方面:InitializeThreads 先建立 THREAD_NUM 個線程,擴容時同樣呼叫它;Process 是線程主體,內部會視情況呼叫 AddThread 與 DeleteThread 完成伸縮;AddWork 投遞任務;ThreadDestroy 負責收尾;AddThread 一次擴充 THREAD_NUM 個線程;DeleteThread 在佇列空閒時把線程數收回 THREAD_NUM。
#ifndef COMMAND_H_ #define COMMAND_H_ class Command { public: int get_cmd(); char* get_arg(); void set_cmd(int cmd); void set_arg(char* arg); private: int cmd_; char arg_[65]; }; #endif /* COMMAND_H_ */
#include <string.h> #include "command.h" int Command::get_cmd() { return cmd_; } char* Command::get_arg() { return arg_; } void Command::set_cmd(int cmd) { cmd_ = cmd; } void Command::set_arg(char* arg) { if(NULL == arg) { return; } strncpy(arg_,arg,64); arg_[64] = '\0'; }
#ifndef THREAD_PROCESS_H_ #define THREAD_PROCESS_H_ class ThreadProcess { public: void Process0(void* arg); void Process1(void* arg); void Process2(void* arg); }; #endif /* THREAD_PROCESS_H_ */
#include <pthread.h> #include <stdio.h> #include <unistd.h> #include "thread_process.h" void ThreadProcess::Process0(void* arg) { printf("thread %u is starting process %s\n",pthread_self(),arg); usleep(100*1000); } void ThreadProcess::Process1(void* arg) { printf("thread %u is starting process %s\n",pthread_self(),arg); usleep(100*1000); } void ThreadProcess::Process2(void* arg) { printf("thread %u is starting process %s\n",pthread_self(),arg); usleep(100*1000); }
#ifndef THREAD_POOL_H_ #define THREAD_POOL_H_ #include <map> #include <vector> #include "command.h" #define MAX_THREAD_NUM 50 // 該值目前需要設定為初始線程數的整數倍 #define ADD_FACTOR 40 // 該值表示一個線程可以處理的最大任務數 #define THREAD_NUM 10 // 初始線程數 class ThreadPool { public: ThreadPool() {}; static void InitializeThreads(); void AddWork(Command command); void ThreadDestroy(int iwait = 2); private: static void* Process(void* arg); static void AddThread(); static void DeleteThread(); static bool bshutdown_; static int icurr_thread_num_; static std::map<pthread_t,int> thread_id_map_; static std::vector<Command> command_; static pthread_mutex_t command_mutex_; static pthread_cond_t command_cond_; }; #endif /* THREAD_POOL_H_ */
#include <pthread.h> #include <stdlib.h> #include "thread_pool.h" #include "thread_process.h" #include "command.h" bool ThreadPool::bshutdown_ = false; int ThreadPool::icurr_thread_num_ = THREAD_NUM; std::vector<Command> ThreadPool::command_; std::map<pthread_t,int> ThreadPool::thread_id_map_; pthread_mutex_t ThreadPool::command_mutex_ = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t ThreadPool::command_cond_ = PTHREAD_COND_INITIALIZER; void ThreadPool::InitializeThreads() { for (int i = 0; i < THREAD_NUM ; ++i) { pthread_t tempThread; pthread_create(&tempThread, NULL, ThreadPool::Process, NULL); thread_id_map_[tempThread] = 0; } } void* ThreadPool::Process(void* arg) { ThreadProcess threadprocess; Command command; while (true) { pthread_mutex_lock(&command_mutex_); // 如果線程需要退出,則此時退出 if (1 == thread_id_map_[pthread_self()]) { pthread_mutex_unlock(&command_mutex_); printf("thread %u will exit\n", pthread_self()); pthread_exit(NULL); } // 當線程不需要退出且沒有需要處理的任務時,需要縮容的則縮容,不需要的則等待信號 if (0 == command_.size() && !bshutdown_) { if(MAX_THREAD_NUM != THREAD_NUM) { DeleteThread(); if (1 == thread_id_map_[pthread_self()]) { pthread_mutex_unlock(&command_mutex_); printf("thread %u will exit\n", pthread_self()); pthread_exit(NULL); } } pthread_cond_wait(&command_cond_,&command_mutex_); } // 線程池需要關閉,關閉已有的鎖,線程退出 if(bshutdown_) { pthread_mutex_unlock (&command_mutex_); printf ("thread %u will exit\n", pthread_self ()); pthread_exit (NULL); } // 如果線程池的最大線程數不等於初始線程數,則表明需要擴容 if(MAX_THREAD_NUM != THREAD_NUM) { AddThread(); } // 從容器中取出待辦任務 std::vector<Command>::iterator iter = command_.begin(); command.set_arg(iter->get_arg()); command.set_cmd(iter->get_cmd()); command_.erase(iter); pthread_mutex_unlock(&command_mutex_); // 開始業務處理 switch(command.get_cmd()) { case 0: threadprocess.Process0(command.get_arg()); break; case 1: threadprocess.Process1(command.get_arg()); break; case 2: threadprocess.Process2(command.get_arg()); break; default: break; } } return NULL; // 完全為了消除警告(eclipse編寫的代碼,警告很煩人) } void ThreadPool::AddWork(Command command) { bool bsignal = false; pthread_mutex_lock(&command_mutex_); if (0 == command_.size()) { bsignal = true; } command_.push_back(command); pthread_mutex_unlock(&command_mutex_); if (bsignal) { pthread_cond_signal(&command_cond_); } } void ThreadPool::ThreadDestroy(int iwait) { while(0 != command_.size()) { sleep(abs(iwait)); } bshutdown_ = true; pthread_cond_broadcast(&command_cond_); std::map<pthread_t,int>::iterator iter = thread_id_map_.begin(); for (; iter!=thread_id_map_.end(); ++iter) { pthread_join(iter->first,NULL); } pthread_mutex_destroy(&command_mutex_); pthread_cond_destroy(&command_cond_); } void ThreadPool::AddThread() { if(((icurr_thread_num_*ADD_FACTOR) < command_.size()) && (MAX_THREAD_NUM != icurr_thread_num_)) { InitializeThreads(); icurr_thread_num_ += THREAD_NUM; } } void ThreadPool::DeleteThread() { int size = icurr_thread_num_ - THREAD_NUM; std::map<pthread_t,int>::iterator iter = thread_id_map_.begin(); for(int i=0; i<size; ++i,++iter) { iter->second = 1; } }
#include "thread_pool.h" #include "command.h" int main() { ThreadPool thread_pool; thread_pool.InitializeThreads(); Command command; char arg[8] = {0}; for(int i=1; i<=1000; ++i) { command.set_cmd(i%3); sprintf(arg,"%d",i); command.set_arg(arg); thread_pool.AddWork(command); } sleep(10); // 用於測試線程池縮容 thread_pool.ThreadDestroy(); return 0; }
程式碼依 Google 開源 C++ 編碼規範撰寫,只要改動那幾個巨集就能調整初始線程數、上限與擴容門檻。有問題歡迎一起討論。