C++實(shí)現(xiàn)一個(gè)簡單的線程池的示例代碼
一、設(shè)計(jì)
線程池應(yīng)該包括
- 保存線程的容器,保存任務(wù)的容器。
- 為了能保證避免線程對(duì)任務(wù)的競態(tài)獲取,需要對(duì)任務(wù)隊(duì)列進(jìn)行加鎖。
- 為了使得工作線程感知任務(wù)的到來,需要使用條件變量來喚醒工作線程。
- 任務(wù)容器中的任務(wù)管理。
- 任務(wù)的處理API。
二、參數(shù)選擇
使用數(shù)組存放線程,鏈表存放任務(wù)。

三、類設(shè)計(jì)
線程池類
template<typename T>
class threadpool
{
public:
threadpool(int thread_num,int max_request);
~threadpool();
bool append(T* request); // 在任務(wù)隊(duì)列中添加任務(wù)
private:
static void worker(void* arg);
void run();
private:
int m_thread_num; // 線程池中的線程數(shù)
int m_max_request; // 任務(wù)隊(duì)列最大保存的任務(wù)數(shù)
pthread_t *m_threads; // 保存線程的容器
std::list<T*>m_queuework; // 保存任務(wù)的鏈表
sem m_sem; // 通知工作線程任務(wù)到來
lock m_locker; // 互斥訪問任務(wù)隊(duì)列
};
構(gòu)造函數(shù)
template<typename T>
threadpool<T>::threadpool(int thread_num,int max_request):m_thread_num(thread_num),m_max_request(max_request)
{
if(thread_num <=0 || max_request <= 0) throw std::exception();
m_threads = new pthread_t[thread_num];
if(!m_threads) throw std::exception();
for(int i = 0;i < thread_num;++i)
{
// 創(chuàng)建線程
if(pthread_create(m_threads + i, NULL,worker,this)!=0)
{
delete[] m_threads;
throw std::exception();
}
// 分離線程
if(pthread_detach(m_threads[i]))
{
delete[] m_threads;
throw std::exception();
}
}
}
析構(gòu)函數(shù)
template<typename T>
threadpool<T>::~threadpool()
{
delete[] m_trheads;
}
添加任務(wù)函數(shù)
template<typename T>
bool threadpool<T>::append(T* request)
{
m_locker.lock();
if(m_queuework.size() > m_max_request)
{
m_locker.unlock();
return false;
}
m_queuework.push_back(request);
m_locker.unlock();
m_sem.post();
return true;
}
任務(wù)處理函數(shù)
template<typename T>
void* threadpool<T>::worker(void*arg)
{
threadpool* pool = (threadpool*)arg;
pool->run();
return pool;
}
template<typename T>
void threadpool<T>::run()
{
while(true)
{
m_sem.wait();
m_locker.lock();
if(m_queuework.empty())
{
m_locker.unlock();
continue;
}
T* request = m_queuework.front();
m_queuework.pop_front();
m_locker.unlock();
request.process(); // 具體任務(wù)的處理業(yè)務(wù)
}
}
到此這篇關(guān)于C++實(shí)現(xiàn)一個(gè)簡單的線程池的示例代碼的文章就介紹到這了,更多相關(guān)C++ 線程池內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用C++和Direct3D (d3d)獲取屏幕截圖并根據(jù)傳入分辨率進(jìn)行縮放圖片大小(最新推薦)
這篇文章主要介紹了使用C++和Direct3D (d3d)獲取屏幕截圖并根據(jù)傳入分辨率進(jìn)行縮放圖片大小,本文給大家講解的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-04-04
基于Matlab圖像處理的公路裂縫檢測實(shí)現(xiàn)
隨著公路的大量投運(yùn),公路日常養(yǎng)護(hù)和管理已經(jīng)成為制約公路運(yùn)營水平提高的瓶頸,特別是路面狀態(tài)采集、檢測維護(hù)等工作更是對(duì)傳統(tǒng)的公路運(yùn)維模式提出了挑戰(zhàn)。這篇文章主要介紹了如何通過Matlab圖像處理實(shí)現(xiàn)公路裂縫檢測,感興趣的可以了解一下2022-02-02
C語言數(shù)據(jù)類型轉(zhuǎn)換實(shí)例代碼
本文主要介紹C 語言數(shù)據(jù)類型轉(zhuǎn)換,這里通過代碼實(shí)例進(jìn)行詳解,這是C語言基礎(chǔ)部分,需要的朋友可以參考下2016-07-07
HDOJ 1443 約瑟夫環(huán)的最新應(yīng)用分析詳解
本篇文章是對(duì)HDOJ 1443 約瑟夫環(huán)的最新應(yīng)用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05

