线程池 于Linux中的实现
线程池的实现
#pragma once#include "TaskQueue.h"#include "TaskQueue.cpp"#include <iostream>using namespace std;template<typename T>class ThreadPool{public: //创建线程池 ThreadPool(int min, int max); //销毁线程池 ~ThreadPool(); //给线程池添加任务 void addTask(Task<T> task); //获取线程池中工作的线程的个数 int getBusyNum(); //获取线程池中活着的线程的个数 int getAliveNum();private: //工作的线程(消费者线程)任务函数 static void* worker(void* arg); //管理者线程任务函数 static void* manager(void* arg); //单个线程退出 void threadExit();private: TaskQueue<T>* taskQ; pthread_t mangerID; //管理者线程ID pthread_t* threadIDs; //工作的线程ID int minNum; //最小线程数量 int maxNum; //最大线程数量 int busyNum; //忙的线程的个数 int liveNum; //存活的线程的个数 int exitNum; //要销毁的线程个数 pthread_mutex_t mutexPool; //锁整个的线程池 pthread_cond_t notEmpty; //任务队列是不是空了 bool shutdown; //是不是要销毁线程池,销毁为1,不销毁为0 static const int NUMBER=2; };
#include "ThreadPool.h"#include <string> //c++ string类#include <string.h> //c#include <unistd.h>//创建线程池template<typename T>ThreadPool<T>::ThreadPool(int min, int max){ do { //实例化任务队列 taskQ = new TaskQueue<T>; if (taskQ == nullptr) { cout << "new taskq fail..." << endl; break; } threadIDs = new pthread_t[max]; if (threadIDs == nullptr) { cout << "new pthread_t fail..." << endl; break; } minNum = min; maxNum = max; busyNum = 0; liveNum = min; exitNum = 0; if (pthread_mutex_init(&mutexPool, NULL) != 0 || pthread_cond_init(¬Empty, NULL) != 0) { cout << "mutex or condition init fail..." << endl; } shutdown = false; //线程池 默认不关闭 //创建线程 //第三个参数需要传入的函数地址, //如果是传入类成员方法,再没有实例化对象时是没有确认的地址的, //所以要么将方法声明为外部方法(全局(不能访问成员属性)或者友元(可以访问私有属性,但是不安全(破坏类的封装性,其他类也可以通过这个方法访问))) //要么声明为静态方法(static),所有成员共用一个方法,但是static方法只能访问static属性,所以第四个参数传入this指针,就能访问非static属性(注意加锁防冲突) pthread_create(&mangerID, NULL, manager, this); for (int i = 0; i < min; ++i) { pthread_create(&threadIDs[i], NULL, worker, this); } return; } while (0); if (threadIDs) { delete[] threadIDs; } if (taskQ) { delete taskQ; }}//销毁线程池template<typename T>ThreadPool<T>::~ThreadPool(){ //关闭线程池 shutdown = true; //阻塞回收管理者线程 pthread_join(mangerID, NULL); //唤醒阻塞的消费者线程 for (int i = 0; i< liveNum; i++) { pthread_cond_signal(¬Empty); } //释放堆内存 if (taskQ != nullptr) { delete taskQ; } if (threadIDs) { delete[] threadIDs; } pthread_mutex_destroy(&mutexPool); pthread_cond_destroy(¬Empty);}//给线程池添加任务template<typename T>void ThreadPool<T>::addTask(Task<T> task){ if (shutdown) { return; } //添加任务 taskQ->addTask(task); //自己维护了一个锁 pthread_cond_signal(¬Empty); //打开阻塞的工作线程}//获取线程池中工作的线程的个数template<typename T>int ThreadPool<T>::getBusyNum(){ pthread_mutex_lock(&mutexPool); int busyNum = this->busyNum; pthread_mutex_unlock(&mutexPool); return busyNum;}//获取线程池中活着的线程的个数template<typename T>int ThreadPool<T>::getAliveNum(){ pthread_mutex_lock(&mutexPool); int liveNum = this->liveNum; pthread_mutex_unlock(&mutexPool); return liveNum;}//工作的线程(消费者线程)任务函数template<typename T>void* ThreadPool<T>::worker(void* arg){ ThreadPool* pool = static_cast<ThreadPool*>(arg); while (true) { pthread_mutex_lock(&pool->mutexPool); //当前队列是否为空 while (pool->taskQ->taskNumber() == 0 && !pool->shutdown) { //通过条件变量 阻塞工作线程 //当线程池工作队列为空 且 没有关闭线程池的情况下 调用pthread_cond_wait进行工作线程阻塞并释放锁pool->mutexPool,让生产者线程去生产 pthread_cond_wait(&pool->notEmpty, &pool->mutexPool); //判断是不是要销毁线程 if (pool->exitNum > 0) { pool->exitNum--; if (pool->liveNum > pool->minNum) { pool->liveNum--; pthread_mutex_unlock(&pool->mutexPool); pool->threadExit(); } } } //判断线程池是否被关闭了 if (pool->shutdown) { pthread_mutex_unlock(&pool->mutexPool); pool->threadExit(); } //从任务队列中取出一个任务 Task<T> task = pool->taskQ->takeTask(); pool->busyNum++; //解锁 pthread_mutex_unlock(&pool->mutexPool); cout << "thread " << to_string(pthread_self()) << " start working..." << endl; //此时就是在创建的工作线程中通过函数指针进行工作 //前半部分主要是进行任务从任务队列中进行拿取或者销毁 task.function(task.arg); delete task.arg; task.arg = nullptr; cout << "thread " << to_string(pthread_self()) << " end working..." << endl; pthread_mutex_lock(&pool->mutexPool); pool->busyNum--; pthread_mutex_unlock(&pool->mutexPool); } return nullptr;}//管理者线程任务函数template<typename T>void* ThreadPool<T>::manager(void* arg){ ThreadPool* pool = static_cast<ThreadPool*>(arg); while (!pool->shutdown) { //每隔3s检测一次 sleep(3); //取出线程池中任务的数量和当前线程的数量 pthread_mutex_lock(&pool->mutexPool); int queueSize = pool->taskQ->taskNumber(); int liveNum = pool->liveNum; //取出忙的线程的数量 int busyNum = pool->busyNum; pthread_mutex_unlock(&pool->mutexPool); //添加线程 //任务的个数>存活的线程个数 && 存活的线程数<最大线程数 if (queueSize > liveNum && liveNum < pool->maxNum) { pthread_mutex_lock(&pool->mutexPool); int counter = 0; for (int i = 0; i < pool->maxNum; i++) { if (pool->threadIDs[i] == 0) { pthread_create(&pool->threadIDs[i], NULL, worker, pool); counter++; pool->liveNum++; } } pthread_mutex_unlock(&pool->mutexPool); } //销毁线程 //忙的线程*2 < 存活的线程数 && 存活的线程数>最小线程数 if (busyNum * 2 < liveNum && liveNum > pool->minNum) { pthread_mutex_lock(&pool->mutexPool); pool->exitNum = NUMBER; pthread_mutex_unlock(&pool->mutexPool); //让工作的线程自杀 for (int i =0; i<NUMBER; i++) { pthread_cond_signal(&pool->notEmpty); /** pthread_cond_wait() 用于阻塞当前线程,等待别的线程使用pthread_cond_signal()或pthread_cond_broadcast来唤醒它。 pthread_cond_wait() 必须与pthread_mutex 配套使用。pthread_cond_wait()函数一进入wait状态就会自动release mutex。 当其他线程通过pthread_cond_signal()或pthread_cond_broadcast,把该线程唤醒, 使pthread_cond_wait()通过(返回)时,该线程又自动获得该mutex。 版权声明:本文为CSDN博主「Geek.Fan」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/fanyun_01/article/details/106975364 */ } } } return nullptr;}//单个线程退出template<typename T>void ThreadPool<T>::threadExit(){ pthread_t tid = pthread_self(); for (int i = 0; i < maxNum; ++i) { if (threadIDs[i] == tid) { threadIDs[i] = 0; cout << "threadExit() called, " << to_string(tid) << " exiting..." << endl; break; } } //pthread_exit c函数不能用nullptr, //此函数是在子线程中调用的,所以退出的是方法调用处的线程。 pthread_exit(NULL); }
任务队列
#pragma once
#include <queue>
#include <pthread.h>
using callback = void(*)(void* arg); //使用using型特性--别名
template<typename T>
struct Task {
Task() {
function = nullptr;
arg = nullptr;
}
Task(callback f, void* arg) {
function = f;
this->arg = (T*)arg;
}
callback function;
T* arg;
};
template<typename T>
class TaskQueue
{
public:
TaskQueue();
~TaskQueue();
//添加任务
void addTask(Task<T> task);
void addTask(callback f, void* arg);
//取出一个任务
Task<T> takeTask();
//获取当前任务的个数
inline int taskNumber()
{
return (int)m_taskQ.size();
}
private:
std::queue<Task<T>> m_taskQ;
pthread_mutex_t m_mutex; //
};
#include "TaskQueue.h"
template<typename T>
TaskQueue<T>::TaskQueue()
{
pthread_mutex_init(&m_mutex, NULL);
}
template<typename T>
TaskQueue<T>::~TaskQueue()
{
pthread_mutex_destroy(&m_mutex);
}
template<typename T>
void TaskQueue<T>::addTask(Task<T> task)
{
pthread_mutex_lock(&m_mutex);
m_taskQ.push(task);
pthread_mutex_unlock(&m_mutex);
}
template<typename T>
void TaskQueue<T>::addTask(callback f, void* arg)
{
pthread_mutex_lock(&m_mutex);
m_taskQ.push(Task<T>(f, arg));
pthread_mutex_unlock(&m_mutex);
}
template<typename T>
Task<T> TaskQueue<T>::takeTask()
{
Task<T> t;
pthread_mutex_lock(&m_mutex);
if (!m_taskQ.empty())
{
t = m_taskQ.front();
m_taskQ.pop();
}
pthread_mutex_unlock(&m_mutex);
return t;
}
测试代码
#include <cstdio>
#include <unistd.h>
#include "ThreadPool.h"
#include "ThreadPool.cpp" //模板类如果头文件与源文件是分别编写的需要将源文件也包含进来
void taskFunc(void* arg)
{
int num = *(int*)arg;
printf("thread %ld is working, number = %d\n", pthread_self(), num);
sleep(1);
}
int main()
{
printf("%s 向你问好!\n", "threadPool");
//创建线程池对象
ThreadPool<int> pool(3, 100);
for (int i = 0; i< 100; i++ )
{
int* num = new int(i+100);
pool.addTask(Task<int>(taskFunc, num));
}
sleep(20);
return 0;
}