服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - 手写线程池 - C 语言版

手写线程池 - C 语言版

2021-12-29 00:41C语言与C++编程 C/C++

在各个编程语言的语种中都有线程池的概念,并且很多语言中直接提供了线程池,作为程序猿直接使用就可以了,下面给大家介绍一下线程池的实现原理。

手写线程池 - C 语言版

1. 线程池原理

我们使用线程的时候就去创建一个线程,这样实现起来非常简便,但是就会有一个问题:如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了,这样频繁创建线程就会大大降低系统的效率,因为频繁创建线程和销毁线程需要时间。

那么有没有一种办法使得线程可以复用,就是执行完一个任务,并不被销毁,而是可以继续执行其他的任务呢?

线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务。线程池线程都是后台线程。每个线程都使用默认的堆栈大小,以默认的优先级运行,并处于多线程单元中。

如果某个线程在托管代码中空闲(如正在等待某个事件), 则线程池将插入另一个辅助线程来使所有处理器保持繁忙。如果所有线程池线程都始终保持繁忙,但队列中包含挂起的工作,则线程池将在一段时间后创建另一个辅助线程但线程的数目永远不会超过最大值。超过最大值的线程可以排队,但他们要等到其他线程完成后才启动。

在各个编程语言的语种中都有线程池的概念,并且很多语言中直接提供了线程池,作为程序猿直接使用就可以了,下面给大家介绍一下线程池的实现原理:

线程池的组成主要分为 3 个部分,这三部分配合工作就可以得到一个完整的线程池:

1).任务队列,存储需要处理的任务,由工作的线程来处理这些任务

  • 通过线程池提供的 API 函数,将一个待处理的任务添加到任务队列,或者从任务队列中删除
  • 已处理的任务会被从任务队列中删除
  • 线程池的使用者,也就是调用线程池函数往任务队列中添加任务的线程就是生产者线程

2).工作的线程(任务队列任务的消费者) ,N个

  • 线程池中维护了一定数量的工作线程,他们的作用是是不停的读任务队列,从里边取出任务并处理
  • 工作的线程相当于是任务队列的消费者角色,
  • 如果任务队列为空,工作的线程将会被阻塞 (使用条件变量 / 信号量阻塞)
  • 如果阻塞之后有了新的任务,由生产者将阻塞解除,工作线程开始工作

3).管理者线程(不处理任务队列中的任务),1个

  • 它的任务是周期性的对任务队列中的任务数量以及处于忙状态的工作线程个数进行检测
  • 当任务过多的时候,可以适当的创建一些新的工作线程
  • 当任务过少的时候,可以适当的销毁一些工作的线程

手写线程池 - C 语言版

2. 任务队列

  1. // 任务结构体
  2. typedef struct Task
  3. {
  4. void (*function)(void* arg);
  5. void* arg;
  6. }Task;

3. 线程池定义

  1. // 线程池结构体
  2. struct ThreadPool
  3. {
  4. // 任务队列
  5. Task* taskQ;
  6. int queueCapacity; // 容量
  7. int queueSize; // 当前任务个数
  8. int queueFront; // 队头 -> 取数据
  9. int queueRear; // 队尾 -> 放数据
  10.  
  11. pthread_t managerID; // 管理者线程ID
  12. pthread_t *threadIDs; // 工作的线程ID
  13. int minNum; // 最小线程数量
  14. int maxNum; // 最大线程数量
  15. int busyNum; // 忙的线程的个数
  16. int liveNum; // 存活的线程的个数
  17. int exitNum; // 要销毁的线程个数
  18. pthread_mutex_t mutexPool; // 锁整个的线程池
  19. pthread_mutex_t mutexBusy; // 锁busyNum变量
  20. pthread_cond_t notFull; // 任务队列是不是满了
  21. pthread_cond_t notEmpty; // 任务队列是不是空了
  22.  
  23. int shutdown; // 是不是要销毁线程池, 销毁为1, 不销毁为0
  24. };

4. 头文件声明

  1. #ifndef _THREADPOOL_H
  2. #define _THREADPOOL_H
  3.  
  4. typedef struct ThreadPool ThreadPool;
  5. // 创建线程池并初始化
  6. ThreadPool *threadPoolCreate(int min, int max, int queueSize);
  7.  
  8. // 销毁线程池
  9. int threadPoolDestroy(ThreadPool* pool);
  10.  
  11. // 给线程池添加任务
  12. void threadPoolAdd(ThreadPool* pool, void(*func)(void*), void* arg);
  13.  
  14. // 获取线程池中工作的线程的个数
  15. int threadPoolBusyNum(ThreadPool* pool);
  16.  
  17. // 获取线程池中活着的线程的个数
  18. int threadPoolAliveNum(ThreadPool* pool);
  19.  
  20. //////////////////////
  21. // 工作的线程(消费者线程)任务函数
  22. void* worker(void* arg);
  23. // 管理者线程任务函数
  24. void* manager(void* arg);
  25. // 单个线程退出
  26. void threadExit(ThreadPool* pool);
  27. #endif // _THREADPOOL_H

5. 源文件定义

  1. ThreadPool* threadPoolCreate(int min, int max, int queueSize)
  2. {
  3. ThreadPool* pool = (ThreadPool*)malloc(sizeof(ThreadPool));
  4. do
  5. {
  6. if (pool == NULL)
  7. {
  8. printf("malloc threadpool fail...\n");
  9. break;
  10. }
  11.  
  12. pool->threadIDs = (pthread_t*)malloc(sizeof(pthread_t) * max);
  13. if (pool->threadIDs == NULL)
  14. {
  15. printf("malloc threadIDs fail...\n");
  16. break;
  17. }
  18. memset(pool->threadIDs, 0, sizeof(pthread_t) * max);
  19. pool->minNum = min;
  20. pool->maxNum = max;
  21. pool->busyNum = 0;
  22. pool->liveNum = min; // 和最小个数相等
  23. pool->exitNum = 0;
  24.  
  25. if (pthread_mutex_init(&pool->mutexPool, NULL) != 0 ||
  26. pthread_mutex_init(&pool->mutexBusy, NULL) != 0 ||
  27. pthread_cond_init(&pool->notEmpty, NULL) != 0 ||
  28. pthread_cond_init(&pool->notFull, NULL) != 0)
  29. {
  30. printf("mutex or condition init fail...\n");
  31. break;
  32. }
  33.  
  34. // 任务队列
  35. pool->taskQ = (Task*)malloc(sizeof(Task) * queueSize);
  36. pool->queueCapacity = queueSize;
  37. pool->queueSize = 0;
  38. pool->queueFront = 0;
  39. pool->queueRear = 0;
  40.  
  41. pool->shutdown = 0;
  42.  
  43. // 创建线程
  44. pthread_create(&pool->managerID, NULL, manager, pool);
  45. for (int i = 0; i < min; ++i)
  46. {
  47. pthread_create(&pool->threadIDs[i], NULL, worker, pool);
  48. }
  49. return pool;
  50. } while (0);
  51.  
  52. // 释放资源
  53. if (pool && pool->threadIDs) free(pool->threadIDs);
  54. if (pool && pool->taskQ) free(pool->taskQ);
  55. if (pool) free(pool);
  56.  
  57. return NULL;
  58. }
  59.  
  60. int threadPoolDestroy(ThreadPool* pool)
  61. {
  62. if (pool == NULL)
  63. {
  64. return -1;
  65. }
  66.  
  67. // 关闭线程池
  68. pool->shutdown = 1;
  69. // 阻塞回收管理者线程
  70. pthread_join(pool->managerID, NULL);
  71. // 唤醒阻塞的消费者线程
  72. for (int i = 0; i < pool->liveNum; ++i)
  73. {
  74. pthread_cond_signal(&pool->notEmpty);
  75. }
  76. // 释放堆内存
  77. if (pool->taskQ)
  78. {
  79. free(pool->taskQ);
  80. }
  81. if (pool->threadIDs)
  82. {
  83. free(pool->threadIDs);
  84. }
  85.  
  86. pthread_mutex_destroy(&pool->mutexPool);
  87. pthread_mutex_destroy(&pool->mutexBusy);
  88. pthread_cond_destroy(&pool->notEmpty);
  89. pthread_cond_destroy(&pool->notFull);
  90.  
  91. free(pool);
  92. pool = NULL;
  93.  
  94. return 0;
  95. }
  96.  
  97.  
  98. void threadPoolAdd(ThreadPool* pool, void(*func)(void*), void* arg)
  99. {
  100. pthread_mutex_lock(&pool->mutexPool);
  101. while (pool->queueSize == pool->queueCapacity && !pool->shutdown)
  102. {
  103. // 阻塞生产者线程
  104. pthread_cond_wait(&pool->notFull, &pool->mutexPool);
  105. }
  106. if (pool->shutdown)
  107. {
  108. pthread_mutex_unlock(&pool->mutexPool);
  109. return;
  110. }
  111. // 添加任务
  112. pool->taskQ[pool->queueRear].function = func;
  113. pool->taskQ[pool->queueRear].arg = arg;
  114. pool->queueRear = (pool->queueRear + 1) % pool->queueCapacity;
  115. pool->queueSize++;
  116.  
  117. pthread_cond_signal(&pool->notEmpty);
  118. pthread_mutex_unlock(&pool->mutexPool);
  119. }
  120.  
  121. int threadPoolBusyNum(ThreadPool* pool)
  122. {
  123. pthread_mutex_lock(&pool->mutexBusy);
  124. int busyNum = pool->busyNum;
  125. pthread_mutex_unlock(&pool->mutexBusy);
  126. return busyNum;
  127. }
  128.  
  129. int threadPoolAliveNum(ThreadPool* pool)
  130. {
  131. pthread_mutex_lock(&pool->mutexPool);
  132. int aliveNum = pool->liveNum;
  133. pthread_mutex_unlock(&pool->mutexPool);
  134. return aliveNum;
  135. }
  136.  
  137. void* worker(void* arg)
  138. {
  139. ThreadPool* pool = (ThreadPool*)arg;
  140.  
  141. while (1)
  142. {
  143. pthread_mutex_lock(&pool->mutexPool);
  144. // 当前任务队列是否为空
  145. while (pool->queueSize == 0 && !pool->shutdown)
  146. {
  147. // 阻塞工作线程
  148. pthread_cond_wait(&pool->notEmpty, &pool->mutexPool);
  149.  
  150. // 判断是不是要销毁线程
  151. if (pool->exitNum > 0)
  152. {
  153. pool->exitNum--;
  154. if (pool->liveNum > pool->minNum)
  155. {
  156. pool->liveNum--;
  157. pthread_mutex_unlock(&pool->mutexPool);
  158. threadExit(pool);
  159. }
  160. }
  161. }
  162.  
  163. // 判断线程池是否被关闭了
  164. if (pool->shutdown)
  165. {
  166. pthread_mutex_unlock(&pool->mutexPool);
  167. threadExit(pool);
  168. }
  169.  
  170. // 从任务队列中取出一个任务
  171. Task task;
  172. task.function = pool->taskQ[pool->queueFront].function;
  173. task.arg = pool->taskQ[pool->queueFront].arg;
  174. // 移动头结点
  175. pool->queueFront = (pool->queueFront + 1) % pool->queueCapacity;
  176. pool->queueSize--;
  177. // 解锁
  178. pthread_cond_signal(&pool->notFull);
  179. pthread_mutex_unlock(&pool->mutexPool);
  180.  
  181. printf("thread %ld start working...\n", pthread_self());
  182. pthread_mutex_lock(&pool->mutexBusy);
  183. pool->busyNum++;
  184. pthread_mutex_unlock(&pool->mutexBusy);
  185. task.function(task.arg);
  186. free(task.arg);
  187. task.arg = NULL;
  188.  
  189. printf("thread %ld end working...\n", pthread_self());
  190. pthread_mutex_lock(&pool->mutexBusy);
  191. pool->busyNum--;
  192. pthread_mutex_unlock(&pool->mutexBusy);
  193. }
  194. return NULL;
  195. }
  196.  
  197. void* manager(void* arg)
  198. {
  199. ThreadPool* pool = (ThreadPool*)arg;
  200. while (!pool->shutdown)
  201. {
  202. // 每隔3s检测一次
  203. sleep(3);
  204.  
  205. // 取出线程池中任务的数量和当前线程的数量
  206. pthread_mutex_lock(&pool->mutexPool);
  207. int queueSize = pool->queueSize;
  208. int liveNum = pool->liveNum;
  209. pthread_mutex_unlock(&pool->mutexPool);
  210.  
  211. // 取出忙的线程的数量
  212. pthread_mutex_lock(&pool->mutexBusy);
  213. int busyNum = pool->busyNum;
  214. pthread_mutex_unlock(&pool->mutexBusy);
  215.  
  216. // 添加线程
  217. // 任务的个数>存活的线程个数 && 存活的线程数<最大线程数
  218. if (queueSize > liveNum && liveNum < pool->maxNum)
  219. {
  220. pthread_mutex_lock(&pool->mutexPool);
  221. int counter = 0;
  222. for (int i = 0; i < pool->maxNum && counter < NUMBER
  223. && pool->liveNum < pool->maxNum; ++i)
  224. {
  225. if (pool->threadIDs[i] == 0)
  226. {
  227. pthread_create(&pool->threadIDs[i], NULL, worker, pool);
  228. counter++;
  229. pool->liveNum++;
  230. }
  231. }
  232. pthread_mutex_unlock(&pool->mutexPool);
  233. }
  234. // 销毁线程
  235. // 忙的线程*2 < 存活的线程数 && 存活的线程>最小线程数
  236. if (busyNum * 2 < liveNum && liveNum > pool->minNum)
  237. {
  238. pthread_mutex_lock(&pool->mutexPool);
  239. pool->exitNum = NUMBER;
  240. pthread_mutex_unlock(&pool->mutexPool);
  241. // 让工作的线程自杀
  242. for (int i = 0; i < NUMBER; ++i)
  243. {
  244. pthread_cond_signal(&pool->notEmpty);
  245. }
  246. }
  247. }
  248. return NULL;
  249. }
  250.  
  251. void threadExit(ThreadPool* pool)
  252. {
  253. pthread_t tid = pthread_self();
  254. for (int i = 0; i < pool->maxNum; ++i)
  255. {
  256. if (pool->threadIDs[i] == tid)
  257. {
  258. pool->threadIDs[i] = 0;
  259. printf("threadExit() called, %ld exiting...\n", tid);
  260. break;
  261. }
  262. }
  263. pthread_exit(NULL);
  264. }

6. 测试代码

  1. void taskFunc(void* arg)
  2. {
  3. int num = *(int*)arg;
  4. printf("thread %ld is working, number = %d\n",
  5. pthread_self(), num);
  6. sleep(1);
  7. }
  8.  
  9. int main()
  10. {
  11. // 创建线程池
  12. ThreadPool* pool = threadPoolCreate(3, 10, 100);
  13. for (int i = 0; i < 100; ++i)
  14. {
  15. int* num = (int*)malloc(sizeof(int));
  16. *num = i + 100;
  17. threadPoolAdd(pool, taskFunc, num);
  18. }
  19.  
  20. sleep(30);
  21.  
  22. threadPoolDestroy(pool);
  23. return 0;
  24. }

原文地址:https://mp.weixin.qq.com/s/XQzDtohIP4qMqJZ-CJXdqA

延伸 · 阅读

精彩推荐