網站首頁 編程語言 正文
一、設計
線程池應該包括
- 保存線程的容器,保存任務的容器。
- 為了能保證避免線程對任務的競態獲取,需要對任務隊列進行加鎖。
- 為了使得工作線程感知任務的到來,需要使用條件變量來喚醒工作線程。
- 任務容器中的任務管理。
- 任務的處理API。
二、參數選擇
使用數組存放線程,鏈表存放任務。
三、類設計
線程池類
template<typename T>
class threadpool
{
public:
threadpool(int thread_num,int max_request);
~threadpool();
bool append(T* request); // 在任務隊列中添加任務
private:
static void worker(void* arg);
void run();
private:
int m_thread_num; // 線程池中的線程數
int m_max_request; // 任務隊列最大保存的任務數
pthread_t *m_threads; // 保存線程的容器
std::list<T*>m_queuework; // 保存任務的鏈表
sem m_sem; // 通知工作線程任務到來
lock m_locker; // 互斥訪問任務隊列
};
構造函數
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)
{
// 創建線程
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();
}
}
}
析構函數
template<typename T>
threadpool<T>::~threadpool()
{
delete[] m_trheads;
}
添加任務函數
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;
}
任務處理函數
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(); // 具體任務的處理業務
}
}
原文鏈接:https://blog.csdn.net/qq_43363657/article/details/124823909
相關推薦
- 2022-07-13 Pycharm使用技巧_Pycharm配置autopep8
- 2022-09-12 Shell編程之/bin/bash和/bin/sh的區別淺析_linux shell
- 2023-03-16 Python?import導入上級目錄文件的方法_python
- 2022-07-16 Electron項目中的NSIS配置項
- 2022-06-08 FreeRTOS編碼標準及風格指南_操作系統
- 2024-03-08 Spring bean的實例化方式之靜態工廠和實例工廠的區別
- 2022-09-08 python如何獲取tensor()數據類型中的值_python
- 2022-12-24 利用C語言實現頁面置換算法的詳細過程_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支