线程池原理详解及如何用C语言实现线程池

网络 通信技术
线程池是一种多线程处理形式,大多用于高并发服务器上,它能合理有效的利用高并发服务器上的线程资源;线程与进程用于处理各项分支子功能,我们通常的操作是:接收消息 ==> 消息分类 ==> 线程创建 ==> 传递消息到子线程 ==> 线程分离 ==> 在子线程中执行任务 ==> 任务结束退出。

 线程池是一种多线程处理形式,大多用于高并发服务器上,它能合理有效的利用高并发服务器上的线程资源;线程与进程用于处理各项分支子功能,我们通常的操作是:接收消息 ==> 消息分类 ==> 线程创建 ==> 传递消息到子线程 ==> 线程分离 ==> 在子线程中执行任务 ==> 任务结束退出;

[[317565]]

对大多数小型局域网的通信来说,上述方法足够满足需求;但当我们的通信范围扩大到广域网或大型局域网通信中时,我们将面临大量消息频繁请求服务器;在这种情况下,创建与销毁线程都已经成为一种奢侈的开销,特别对于嵌入式服务器来说更应保证内存资源的合理利用;

因此,线程池技术应运而生;线程池允许一个线程可以多次复用,且每次复用的线程内部的消息处理可以不相同,将创建与销毁的开销省去而不必来一个请求开一个线程;

结构讲解:

线程池是一个抽象的概念,其内部由任务队列,一堆线程,管理者线程组成;

线程池原理详解及如何用C语言实现线程池

我们将以上图为例,实现一个最基础的线程池,接下来将分部分依次讲解;讲解顺序为:1.线程池总体结构 2.线程数组 3.任务队列 4.管理者线程 5.使用线程池接口的例子

一、线程池总体结构

这里讲解线程池在逻辑上的结构体;看下方代码,该结构体threadpool_t中包含线程池状态信息,任务队列信息以及多线程操作中的互斥锁;在任务结构体中包含了一个可以放置多种不同任务函数的函数指针,一个传入该任务函数的void*类型的参数;

注意:在使用时需要将你的消息分类处理函数装入任务的(*function);然后放置到任务队列并通知空闲线程;

线程池状态信息:描述当前线程池的基本信息,如是否开启、最小线程数、最大线程数、存活线程数、忙线程数、待销毁线程数等… …

任务队列信息:描述当前任务队列基本信息,如最大任务数、队列不为满条件变量、队列不为空条件变量等… …

多线程互斥锁:保证在同一时间点上只有一个线程在任务队列中取任务并修改任务队列信息、修改线程池信息;

函数指针:在打包消息阶段,将分类后的消息处理函数放在(*function);

void*类型参数:用于传递消息处理函数需要的信息;

  1. /*任务*/ 
  2. typedef struct { 
  3. void *(*function)(void *); 
  4. void *arg; 
  5. } threadpool_task_t; 
  6. /*线程池管理*/ 
  7. struct threadpool_t{ 
  8. pthread_mutex_t lock; /* 锁住整个结构体 */ 
  9. pthread_mutex_t thread_counter; /* 用于使用忙线程数时的锁 */ 
  10. pthread_cond_t queue_not_full; /* 条件变量,任务队列不为满 */ 
  11. pthread_cond_t queue_not_empty; /* 任务队列不为空 */ 
  12. pthread_t *threads; /* 存放线程的tid,实际上就是管理了线 数组 */ 
  13. pthread_t admin_tid; /* 管理者线程tid */ 
  14. threadpool_task_t *task_queue; /* 任务队列 */ 
  15. /*线程池信息*/ 
  16. int min_thr_num; /* 线程池中最小线程数 */ 
  17. int max_thr_num; /* 线程池中最大线程数 */ 
  18. int live_thr_num; /* 线程池中存活的线程数 */ 
  19. int busy_thr_num; /* 忙线程,正在工作的线程 */ 
  20. int wait_exit_thr_num; /* 需要销毁的线程数 */ 
  21. /*任务队列信息*/ 
  22. int queue_front; /* 队头 */ 
  23. int queue_rear; /* 队尾 */ 
  24. int queue_size; 
  25. /* 存在的任务数 */ 
  26. int queue_max_size; /* 队列能容纳的最大任务数 */ 
  27. /*线程池状态*/ 
  28. int shutdown; /* true为关闭 */ 
  29. }; 
  30. **/*创建线程池*/** 
  31. threadpool_t * 
  32. threadpool_create(int min_thr_num, int max_thr_num, int queue_max_size) 
  33. { /* 最小线程数 最大线程数 最大任务数*/ 
  34. int i; 
  35. threadpool_t *pool = NULL
  36. do 
  37. /* 线程池空间开辟 */ 
  38. if ((pool=(threadpool_t *)malloc(sizeof(threadpool_t))) == NULL
  39. printf("malloc threadpool false; \n"); 
  40. break; 
  41. /*信息初始化*/ 
  42. pool->min_thr_num = min_thr_num; 
  43. pool->max_thr_num = max_thr_num; 
  44. pool->busy_thr_num = 0; 
  45. pool->live_thr_num = min_thr_num; 
  46. pool->wait_exit_thr_num = 0; 
  47. pool->queue_front = 0; 
  48. pool->queue_rear = 0; 
  49. pool->queue_size = 0; 
  50. pool->queue_max_size = queue_max_size; 
  51. pool->shutdown = false
  52. /* 根据最大线程数,给工作线程数组开空间,清0 */ 
  53. pool->threads = (pthread_t *)malloc(sizeof(pthread_t)*max_thr_num); 
  54. if (pool->threads == NULL
  55. printf("malloc threads false;\n"); 
  56. break; 
  57. memset(pool->threads, 0, sizeof(pthread_t)*max_thr_num); 
  58. /* 队列开空间 */ 
  59. pool->task_queue = 
  60. (threadpool_task_t *)malloc(sizeof(threadpool_task_t)*queue_max_size); 
  61. if (pool->task_queue == NULL
  62. printf("malloc task queue false;\n"); 
  63. break; 
  64. /* 初始化互斥锁和条件变量 */ 
  65. if ( pthread_mutex_init(&(pool->lock), NULL) != 0 || 
  66. pthread_mutex_init(&(pool->thread_counter), NULL) !=0 || 
  67. pthread_cond_init(&(pool->queue_not_empty), NULL) !=0 || 
  68. pthread_cond_init(&(pool->queue_not_full), NULL) !=0) 
  69. printf("init lock or cond false;\n"); 
  70. break; 
  71. /* 启动min_thr_num个工作线程 */ 
  72. for (i=0; i<min_thr_num; i++) 
  73. /* pool指向当前线程池 threadpool_thread函数在后面讲解 */ 
  74. pthread_create(&(pool->threads[i]), NULL, threadpool_thread, (void *)pool); 
  75. printf("start thread 0x%x... \n", (unsigned int)pool->threads[i]); 
  76. /* 管理者线程 admin_thread函数在后面讲解 */ 
  77. pthread_create(&(pool->admin_tid), NULL, admin_thread, (void *)pool); 
  78. return pool; 
  79. } while(0); 
  80. /* 释放pool的空间 */ 
  81. threadpool_free(pool); 
  82. return NULL

二、线程数组

线程数组实际上是在线程池初始化时开辟的一段存放一堆线程tid的空间,在逻辑上形成一个池,里面放置着提前创建的线程;这段空间中包含了正在工作的线程,等待工作的线程(空闲线程),等待被销毁的线程,申明但没有初始化的线程空间;

线程池原理详解及如何用C语言实现线程池
  1. /*工作线程*/ 
  2. void * 
  3. threadpool_thread(void *threadpool) 
  4. threadpool_t *pool = (threadpool_t *)threadpool; 
  5. threadpool_task_t task; 
  6. while (true
  7. pthread_mutex_lock(&(pool->lock)); 
  8. /* 无任务则阻塞在 “任务队列不为空” 上,有任务则跳出 */ 
  9. while ((pool->queue_size == 0) && (!pool->shutdown)) 
  10. printf("thread 0x%x is waiting \n", (unsigned int)pthread_self()); 
  11. pthread_cond_wait(&(pool->queue_not_empty), &(pool->lock)); 
  12. /* 判断是否需要清除线程,自杀功能 */ 
  13. if (pool->wait_exit_thr_num > 0) 
  14. pool->wait_exit_thr_num--; 
  15. /* 判断线程池中的线程数是否大于最小线程数,是则结束当前线程 */ 
  16. if (pool->live_thr_num > pool->min_thr_num) 
  17. printf("thread 0x%x is exiting \n", (unsigned int)pthread_self()); 
  18. pool->live_thr_num--; 
  19. pthread_mutex_unlock(&(pool->lock)); 
  20. pthread_exit(NULL);//结束线程 
  21. /* 线程池开关状态 */ 
  22. if (pool->shutdown) //关闭线程池 
  23. pthread_mutex_unlock(&(pool->lock)); 
  24. printf("thread 0x%x is exiting \n", (unsigned int)pthread_self()); 
  25. pthread_exit(NULL); //线程自己结束自己 
  26. //否则该线程可以拿出任务 
  27. task.function = pool->task_queue[pool->queue_front].function; //出队操作 
  28. task.arg = pool->task_queue[pool->queue_front].arg; 
  29. pool->queue_front = (pool->queue_front + 1) % pool->queue_max_size; //环型结构 
  30. pool->queue_size--; 
  31. //通知可以添加新任务 
  32. pthread_cond_broadcast(&(pool->queue_not_full)); 
  33. //释放线程锁 
  34. pthread_mutex_unlock(&(pool->lock)); 
  35. //执行刚才取出的任务 
  36. printf("thread 0x%x start working \n", (unsigned int)pthread_self()); 
  37. pthread_mutex_lock(&(pool->thread_counter)); //锁住忙线程变量 
  38. pool->busy_thr_num++; 
  39. pthread_mutex_unlock(&(pool->thread_counter)); 
  40. (*(task.function))(task.arg); //执行任务 
  41. //任务结束处理 
  42. printf("thread 0x%x end working \n", (unsigned int)pthread_self()); 
  43. pthread_mutex_lock(&(pool->thread_counter)); 
  44. pool->busy_thr_num--; 
  45. pthread_mutex_unlock(&(pool->thread_counter)); 
  46. pthread_exit(NULL); 

三、任务队列

任务队列的存在形式与线程数组相似;在线程池初始化时根据传入的最大任务数开辟空间;当服务器前方后请求到来后,分类并打包消息成为任务,将任务放入任务队列并通知空闲线程来取;不同之处在于任务队列有明显的先后顺序,先进先出;而线程数组中的线程则是一个竞争关系去拿到互斥锁争取任务;

线程池原理详解及如何用C语言实现线程池
  1. /*向线程池的任务队列中添加一个任务*/ 
  2. int 
  3. threadpool_add_task(threadpool_t *pool, void *(*function)(void *arg), void *arg) 
  4. pthread_mutex_lock(&(pool->lock)); 
  5. /*如果队列满了,调用wait阻塞*/ 
  6. while ((pool->queue_size == pool->queue_max_size) && (!pool->shutdown)) 
  7. pthread_cond_wait(&(pool->queue_not_full), &(pool->lock)); 
  8. /*如果线程池处于关闭状态*/ 
  9. if (pool->shutdown) 
  10. pthread_mutex_unlock(&(pool->lock)); 
  11. return -1; 
  12. /*清空工作线程的回调函数的参数arg*/ 
  13. if (pool->task_queue[pool->queue_rear].arg != NULL
  14. free(pool->task_queue[pool->queue_rear].arg); 
  15. pool->task_queue[pool->queue_rear].arg = NULL
  16. /*添加任务到任务队列*/ 
  17. pool->task_queue[pool->queue_rear].function = function
  18. pool->task_queue[pool->queue_rear].arg = arg; 
  19. pool->queue_rear = (pool->queue_rear + 1) % pool->queue_max_size; /* 逻辑环 */ 
  20. pool->queue_size++; 
  21. /*添加完任务后,队列就不为空了,唤醒线程池中的一个线程*/ 
  22. pthread_cond_signal(&(pool->queue_not_empty)); 
  23. pthread_mutex_unlock(&(pool->lock)); 
  24. return 0; 

四、管理者线程

作为线程池的管理者,该线程的主要功能包括:检查线程池内线程的存活状态,工作状态;负责根据服务器当前的请求状态去动态的增加或删除线程,保证线程池中的线程数量维持在一个合理高效的平衡上;

说到底,它就是一个单独的线程,定时的去检查,根据我们的一个维持平衡算法去增删线程;

  1. /*管理线程*/ 
  2. void * 
  3. admin_thread(void *threadpool) 
  4. int i; 
  5. threadpool_t *pool = (threadpool_t *)threadpool; 
  6. while (!pool->shutdown) 
  7. printf("admin -----------------\n"); 
  8. sleep(DEFAULT_TIME); /*隔一段时间再管理*/ 
  9. pthread_mutex_lock(&(pool->lock)); /*加锁*/ 
  10. int queue_size = pool->queue_size; /*任务数*/ 
  11. int live_thr_num = pool->live_thr_num; /*存活的线程数*/ 
  12. pthread_mutex_unlock(&(pool->lock)); /*解锁*/ 
  13. pthread_mutex_lock(&(pool->thread_counter)); 
  14. int busy_thr_num = pool->busy_thr_num; /*忙线程数*/ 
  15. pthread_mutex_unlock(&(pool->thread_counter)); 
  16. printf("admin busy live -%d--%d-\n", busy_thr_num, live_thr_num); 
  17. /*创建新线程 实际任务数量大于 最小正在等待的任务数量,存活线程数小于最大线程数*/ 
  18. if (queue_size >= MIN_WAIT_TASK_NUM && live_thr_num <= pool->max_thr_num) 
  19. printf("admin add-----------\n"); 
  20. pthread_mutex_lock(&(pool->lock)); 
  21. int add=0; 
  22. /*一次增加 DEFAULT_THREAD_NUM 个线程*/ 
  23. for (i=0; i<pool->max_thr_num && add<DEFAULT_THREAD_NUM 
  24. && pool->live_thr_num < pool->max_thr_num; i++) 
  25. if (pool->threads[i] == 0 || !is_thread_alive(pool->threads[i])) 
  26. pthread_create(&(pool->threads[i]), NULL, threadpool_thread, (void *)pool); 
  27. add++; 
  28. pool->live_thr_num++; 
  29. printf("new thread -----------------------\n"); 
  30. pthread_mutex_unlock(&(pool->lock)); 
  31. /*销毁多余的线程 忙线程x2 都小于 存活线程,并且存活的大于最小线程数*/ 
  32. if ((busy_thr_num*2) < live_thr_num && live_thr_num > pool->min_thr_num) 
  33. // printf("admin busy --%d--%d----\n", busy_thr_num, live_thr_num); 
  34. /*一次销毁DEFAULT_THREAD_NUM个线程*/ 
  35. pthread_mutex_lock(&(pool->lock)); 
  36. pool->wait_exit_thr_num = DEFAULT_THREAD_NUM; 
  37. pthread_mutex_unlock(&(pool->lock)); 
  38. for (i=0; i<DEFAULT_THREAD_NUM; i++) 
  39. //通知正在处于空闲的线程,自杀 
  40. pthread_cond_signal(&(pool->queue_not_empty)); 
  41. printf("admin cler --\n"); 
  42. return NULL
  43. /*线程是否存活*/ 
  44. int 
  45. is_thread_alive(pthread_t tid) 
  46. int kill_rc = pthread_kill(tid, 0); //发送0号信号,测试是否存活 
  47. if (kill_rc == ESRCH) //线程不存在 
  48. return false
  49. return true

五、释放

  1. /*释放线程池*/ 
  2. int 
  3. threadpool_free(threadpool_t *pool) 
  4. if (pool == NULL
  5. return -1; 
  6. if (pool->task_queue) 
  7. free(pool->task_queue); 
  8. if (pool->threads) 
  9. free(pool->threads); 
  10. pthread_mutex_lock(&(pool->lock)); /*先锁住再销毁*/ 
  11. pthread_mutex_destroy(&(pool->lock)); 
  12. pthread_mutex_lock(&(pool->thread_counter)); 
  13. pthread_mutex_destroy(&(pool->thread_counter)); 
  14. pthread_cond_destroy(&(pool->queue_not_empty)); 
  15. pthread_cond_destroy(&(pool->queue_not_full)); 
  16. free(pool); 
  17. pool = NULL
  18. return 0; 
  19. /*销毁线程池*/ 
  20. int 
  21. threadpool_destroy(threadpool_t *pool) 
  22. int i; 
  23. if (pool == NULL
  24. return -1; 
  25. pool->shutdown = true
  26. /*销毁管理者线程*/ 
  27. pthread_join(pool->admin_tid, NULL); 
  28. //通知所有线程去自杀(在自己领任务的过程中) 
  29. for (i=0; i<pool->live_thr_num; i++) 
  30. pthread_cond_broadcast(&(pool->queue_not_empty)); 
  31. /*等待线程结束 先是pthread_exit 然后等待其结束*/ 
  32. for (i=0; i<pool->live_thr_num; i++) 
  33. pthread_join(pool->threads[i], NULL); 
  34. threadpool_free(pool); 
  35. return 0; 

六、接口

  1. /* 线程池初始化,其管理者线程及工作线程都会启动 */ 
  2. threadpool_t *thp = threadpool_create(10, 100, 100); 
  3. printf("threadpool init ... ... \n"); 
  4. /* 接收到任务后添加 */ 
  5. threadpool_add_task(thp, do_work, (void *)p); 
  6. // ... ... 
  7. /* 销毁 */ 
  8. threadpool_destroy(thp); 

 

 

责任编辑:武晓燕 来源: 今日头条
相关推荐

2012-05-15 02:18:31

Java线程池

2020-12-10 08:24:40

线程池线程方法

2021-12-28 15:10:01

线程池C语言编程语言

2021-09-11 07:32:15

Java线程线程池

2018-10-31 15:54:47

Java线程池源码

2023-08-02 08:03:08

Python线程池

2023-05-19 08:01:24

Key消费场景

2022-11-09 09:01:08

并发编程线程池

2012-02-01 11:20:23

Java线程

2023-11-29 16:38:12

线程池阻塞队列开发

2021-05-26 11:30:24

Java线程池代码

2022-09-26 00:48:14

线程池阻塞数据

2023-10-13 08:20:02

Spring线程池id

2021-07-16 11:35:20

Java线程池代码

2009-07-22 09:39:18

CLR线程池

2020-10-19 10:01:12

Nodejs线程池设计

2011-08-30 12:51:19

MySQL线程缓冲池

2021-06-24 08:02:35

线程池Java代码

2022-03-09 09:43:01

工具类线程项目

2021-02-06 14:02:55

线程池Builder模式
点赞
收藏

51CTO技术栈公众号