• Linux 下 C语言版本的线程池


    目录

    1. 线程池引入

    2. 线程池介绍

    3. 线程池的组成

    4. 任务队列

    5. 线程池定义

    6. 头文件声明

    7. 函数实现

    8. 测试代码


    1. 线程池引入

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

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

    2. 线程池介绍

            线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务。线程池线程都是后台线程。每个线程都使用默认的堆栈大小,以默认的优先级运行,并处于多线程单元中。如果某个线程在托管代码中空闲(如正在等待某个事件), 则线程池将插入另一个辅助线程来使所有处理器保持繁忙。如果所有线程池线程都始终保持繁忙,但队列中包含挂起的工作,则线程池将在一段时间后创建另一个辅助线程但线程的数目永远不会超过最大值。超过最大值的线程可以排队,但他们要等到其他线程完成后才启动。

    3. 线程池的组成

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

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

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

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

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

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

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

    4. 任务队列

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

    5. 线程池定义

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

    6. 头文件声明

    1. #ifndef __THREADPOOL_H
    2. #define __THREADPOOL_H
    3. typedef struct ThreadPool ThreadPool; // 声明一下,说明该结构体在其他方定义了
    4. // 创建线程池并初始化
    5. ThreadPool* threadPoolCreate(int min, int max, int queueSize);
    6. // 销毁线程池
    7. int threadPoolDestroy(ThreadPool* pool);
    8. // 给线程池添加任务
    9. void threadPoolAdd(ThreadPool* pool, void(*func)(void*),void* arg);
    10. // 获取线程池中工作的线程的个数
    11. int threadPoolBusyNum(ThreadPool* pool);
    12. // 获取线程池中活着的线程个数
    13. int threadPoolAliveNum(ThreadPool* pool);
    14. /
    15. void* worker(void* arg);
    16. void* manager(void* arg);
    17. void threadExit(ThreadPool* pool);
    18. #endif // !__THREADPOOL_H

    7. 函数实现

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

    8. 测试代码

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

    这篇文章来源linux下c语言版线程池_linux c 线程池_zsffuture的博客-CSDN博客,我是根据视频讲解写的代码,测试通过,感觉代码结构设计很好,怕后面找不到,因此搬运过来参考

  • 相关阅读:
    IBL计算总结
    Java 项目-基于微信小程序的自助购药系统
    「中间件」rabbitmq 消息队列基础知识
    第二十三篇:稳定性之服务SLA
    cocos2dx 3D物理相关知识点汇总
    Android 13.0 SystemUI状态栏屏蔽掉通知栏不显示通知
    C++基础系列(一) 对象指针
    大数据学习笔记1.3 Linux用户操作
    Autosar MCAL-ADC详解(一)-基于Tc27x的cfg软件
    Spring MVC ViewNameMethodReturnValueHandler原理解析
  • 原文地址:https://blog.csdn.net/Outside_/article/details/132735859