线程池 于Linux中的实现

线程池的实现

  1. #pragma once
  2. #include "TaskQueue.h"
  3. #include "TaskQueue.cpp"
  4. #include <iostream>
  5. using namespace std;
  6. template<typename T>
  7. class ThreadPool
  8. {
  9. public:
  10. //创建线程池
  11. ThreadPool(int min, int max);
  12. //销毁线程池
  13. ~ThreadPool();
  14. //给线程池添加任务
  15. void addTask(Task<T> task);
  16. //获取线程池中工作的线程的个数
  17. int getBusyNum();
  18. //获取线程池中活着的线程的个数
  19. int getAliveNum();
  20. private:
  21. //工作的线程(消费者线程)任务函数
  22. static void* worker(void* arg);
  23. //管理者线程任务函数
  24. static void* manager(void* arg);
  25. //单个线程退出
  26. void threadExit();
  27. private:
  28. TaskQueue<T>* taskQ;
  29. pthread_t mangerID; //管理者线程ID
  30. pthread_t* threadIDs; //工作的线程ID
  31. int minNum; //最小线程数量
  32. int maxNum; //最大线程数量
  33. int busyNum; //忙的线程的个数
  34. int liveNum; //存活的线程的个数
  35. int exitNum; //要销毁的线程个数
  36. pthread_mutex_t mutexPool; //锁整个的线程池
  37. pthread_cond_t notEmpty; //任务队列是不是空了
  38. bool shutdown; //是不是要销毁线程池,销毁为1,不销毁为0
  39. static const int NUMBER=2;
  40. };
  1. #include "ThreadPool.h"
  2. #include <string> //c++ string类
  3. #include <string.h> //c
  4. #include <unistd.h>
  5. //创建线程池
  6. template<typename T>
  7. ThreadPool<T>::ThreadPool(int min, int max)
  8. {
  9. do
  10. {
  11. //实例化任务队列
  12. taskQ = new TaskQueue<T>;
  13. if (taskQ == nullptr)
  14. {
  15. cout << "new taskq fail..." << endl;
  16. break;
  17. }
  18. threadIDs = new pthread_t[max];
  19. if (threadIDs == nullptr)
  20. {
  21. cout << "new pthread_t fail..." << endl;
  22. break;
  23. }
  24. minNum = min;
  25. maxNum = max;
  26. busyNum = 0;
  27. liveNum = min;
  28. exitNum = 0;
  29. if (pthread_mutex_init(&mutexPool, NULL) != 0 ||
  30. pthread_cond_init(&notEmpty, NULL) != 0)
  31. {
  32. cout << "mutex or condition init fail..." << endl;
  33. }
  34. shutdown = false; //线程池 默认不关闭
  35. //创建线程
  36. //第三个参数需要传入的函数地址,
  37. //如果是传入类成员方法,再没有实例化对象时是没有确认的地址的,
  38. //所以要么将方法声明为外部方法(全局(不能访问成员属性)或者友元(可以访问私有属性,但是不安全(破坏类的封装性,其他类也可以通过这个方法访问)))
  39. //要么声明为静态方法(static),所有成员共用一个方法,但是static方法只能访问static属性,所以第四个参数传入this指针,就能访问非static属性(注意加锁防冲突)
  40. pthread_create(&mangerID, NULL, manager, this);
  41. for (int i = 0; i < min; ++i)
  42. {
  43. pthread_create(&threadIDs[i], NULL, worker, this);
  44. }
  45. return;
  46. } while (0);
  47. if (threadIDs)
  48. {
  49. delete[] threadIDs;
  50. }
  51. if (taskQ)
  52. {
  53. delete taskQ;
  54. }
  55. }
  56. //销毁线程池
  57. template<typename T>
  58. ThreadPool<T>::~ThreadPool()
  59. {
  60. //关闭线程池
  61. shutdown = true;
  62. //阻塞回收管理者线程
  63. pthread_join(mangerID, NULL);
  64. //唤醒阻塞的消费者线程
  65. for (int i = 0; i< liveNum; i++)
  66. {
  67. pthread_cond_signal(&notEmpty);
  68. }
  69. //释放堆内存
  70. if (taskQ != nullptr)
  71. {
  72. delete taskQ;
  73. }
  74. if (threadIDs)
  75. {
  76. delete[] threadIDs;
  77. }
  78. pthread_mutex_destroy(&mutexPool);
  79. pthread_cond_destroy(&notEmpty);
  80. }
  81. //给线程池添加任务
  82. template<typename T>
  83. void ThreadPool<T>::addTask(Task<T> task)
  84. {
  85. if (shutdown)
  86. {
  87. return;
  88. }
  89. //添加任务
  90. taskQ->addTask(task); //自己维护了一个锁
  91. pthread_cond_signal(&notEmpty); //打开阻塞的工作线程
  92. }
  93. //获取线程池中工作的线程的个数
  94. template<typename T>
  95. int ThreadPool<T>::getBusyNum()
  96. {
  97. pthread_mutex_lock(&mutexPool);
  98. int busyNum = this->busyNum;
  99. pthread_mutex_unlock(&mutexPool);
  100. return busyNum;
  101. }
  102. //获取线程池中活着的线程的个数
  103. template<typename T>
  104. int ThreadPool<T>::getAliveNum()
  105. {
  106. pthread_mutex_lock(&mutexPool);
  107. int liveNum = this->liveNum;
  108. pthread_mutex_unlock(&mutexPool);
  109. return liveNum;
  110. }
  111. //工作的线程(消费者线程)任务函数
  112. template<typename T>
  113. void* ThreadPool<T>::worker(void* arg)
  114. {
  115. ThreadPool* pool = static_cast<ThreadPool*>(arg);
  116. while (true)
  117. {
  118. pthread_mutex_lock(&pool->mutexPool);
  119. //当前队列是否为空
  120. while (pool->taskQ->taskNumber() == 0 && !pool->shutdown)
  121. {
  122. //通过条件变量 阻塞工作线程
  123. //当线程池工作队列为空 且 没有关闭线程池的情况下 调用pthread_cond_wait进行工作线程阻塞并释放锁pool->mutexPool,让生产者线程去生产
  124. pthread_cond_wait(&pool->notEmpty, &pool->mutexPool);
  125. //判断是不是要销毁线程
  126. if (pool->exitNum > 0)
  127. {
  128. pool->exitNum--;
  129. if (pool->liveNum > pool->minNum)
  130. {
  131. pool->liveNum--;
  132. pthread_mutex_unlock(&pool->mutexPool);
  133. pool->threadExit();
  134. }
  135. }
  136. }
  137. //判断线程池是否被关闭了
  138. if (pool->shutdown)
  139. {
  140. pthread_mutex_unlock(&pool->mutexPool);
  141. pool->threadExit();
  142. }
  143. //从任务队列中取出一个任务
  144. Task<T> task = pool->taskQ->takeTask();
  145. pool->busyNum++;
  146. //解锁
  147. pthread_mutex_unlock(&pool->mutexPool);
  148. cout << "thread " << to_string(pthread_self()) << " start working..." << endl;
  149. //此时就是在创建的工作线程中通过函数指针进行工作
  150. //前半部分主要是进行任务从任务队列中进行拿取或者销毁
  151. task.function(task.arg);
  152. delete task.arg;
  153. task.arg = nullptr;
  154. cout << "thread " << to_string(pthread_self()) << " end working..." << endl;
  155. pthread_mutex_lock(&pool->mutexPool);
  156. pool->busyNum--;
  157. pthread_mutex_unlock(&pool->mutexPool);
  158. }
  159. return nullptr;
  160. }
  161. //管理者线程任务函数
  162. template<typename T>
  163. void* ThreadPool<T>::manager(void* arg)
  164. {
  165. ThreadPool* pool = static_cast<ThreadPool*>(arg);
  166. while (!pool->shutdown)
  167. {
  168. //每隔3s检测一次
  169. sleep(3);
  170. //取出线程池中任务的数量和当前线程的数量
  171. pthread_mutex_lock(&pool->mutexPool);
  172. int queueSize = pool->taskQ->taskNumber();
  173. int liveNum = pool->liveNum;
  174. //取出忙的线程的数量
  175. int busyNum = pool->busyNum;
  176. pthread_mutex_unlock(&pool->mutexPool);
  177. //添加线程
  178. //任务的个数>存活的线程个数 && 存活的线程数<最大线程数
  179. if (queueSize > liveNum && liveNum < pool->maxNum)
  180. {
  181. pthread_mutex_lock(&pool->mutexPool);
  182. int counter = 0;
  183. for (int i = 0; i < pool->maxNum; i++)
  184. {
  185. if (pool->threadIDs[i] == 0)
  186. {
  187. pthread_create(&pool->threadIDs[i], NULL, worker, pool);
  188. counter++;
  189. pool->liveNum++;
  190. }
  191. }
  192. pthread_mutex_unlock(&pool->mutexPool);
  193. }
  194. //销毁线程
  195. //忙的线程*2 < 存活的线程数 && 存活的线程数>最小线程数
  196. if (busyNum * 2 < liveNum && liveNum > pool->minNum)
  197. {
  198. pthread_mutex_lock(&pool->mutexPool);
  199. pool->exitNum = NUMBER;
  200. pthread_mutex_unlock(&pool->mutexPool);
  201. //让工作的线程自杀
  202. for (int i =0; i<NUMBER; i++)
  203. {
  204. pthread_cond_signal(&pool->notEmpty);
  205. /**
  206. pthread_cond_wait() 用于阻塞当前线程,等待别的线程使用pthread_cond_signal()或pthread_cond_broadcast来唤醒它。
  207. pthread_cond_wait() 必须与pthread_mutex 配套使用。pthread_cond_wait()函数一进入wait状态就会自动release mutex。
  208. 当其他线程通过pthread_cond_signal()或pthread_cond_broadcast,把该线程唤醒,
  209. 使pthread_cond_wait()通过(返回)时,该线程又自动获得该mutex。
  210. 版权声明:本文为CSDN博主「Geek.Fan」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
  211. 原文链接:https://blog.csdn.net/fanyun_01/article/details/106975364
  212. */
  213. }
  214. }
  215. }
  216. return nullptr;
  217. }
  218. //单个线程退出
  219. template<typename T>
  220. void ThreadPool<T>::threadExit()
  221. {
  222. pthread_t tid = pthread_self();
  223. for (int i = 0; i < maxNum; ++i)
  224. {
  225. if (threadIDs[i] == tid)
  226. {
  227. threadIDs[i] = 0;
  228. cout << "threadExit() called, " << to_string(tid) << " exiting..." << endl;
  229. break;
  230. }
  231. }
  232. //pthread_exit c函数不能用nullptr,
  233. //此函数是在子线程中调用的,所以退出的是方法调用处的线程。
  234. pthread_exit(NULL);
  235. }

任务队列

#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;
}