手写线程池 - C 语言版

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

[[442559]]

1. 线程池原理

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

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

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

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

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

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

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

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

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

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

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

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

 

 

 

 

2. 任务队列

 

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

3. 线程池定义

 

  1. // 线程池结构体 
  2. struct ThreadPool 
  3.     // 任务队列 
  4.     Task* taskQ; 
  5.     int queueCapacity;  // 容量 
  6.     int queueSize;      // 当前任务个数 
  7.     int queueFront;     // 队头 -> 取数据 
  8.     int queueRear;      // 队尾 -> 放数据 
  9.  
  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 mutexBusy;  // 锁busyNum变量 
  19.     pthread_cond_t notFull;     // 任务队列是不是满了 
  20.     pthread_cond_t notEmpty;    // 任务队列是不是空了 
  21.  
  22.     int shutdown;           // 是不是要销毁线程池, 销毁为1, 不销毁为0 
  23. }; 

4. 头文件声明

 

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

6. 测试代码

 

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

 

责任编辑:庞桂玉 来源: C语言与C++编程
相关推荐

2013-06-03 09:34:14

崩溃程序程序算法

2020-03-05 15:34:16

线程池C语言局域网

2020-12-10 08:24:40

线程池线程方法

2022-03-09 09:43:01

工具类线程项目

2009-05-29 09:48:05

Sandboxie浏览器

2011-10-21 15:33:45

Dart

2021-02-01 08:28:24

Linux线程池Linux系统

2021-11-11 15:12:21

C语言线程代码

2009-08-04 17:18:02

C#线程

2013-06-24 15:58:19

Windows 8.1Windows 8.1

2011-01-05 11:12:34

C++

2023-05-19 08:01:24

Key消费场景

2021-04-08 11:10:07

C语言版本Cmake

2018-09-20 17:30:01

2018-09-25 14:35:06

zl

2022-09-06 08:31:09

线程池工具系统

2013-04-09 12:18:45

socket.ioC服务器

2012-05-15 02:18:31

Java线程池

2019-12-27 09:09:42

Tomcat线程池JDK

2023-06-07 13:49:00

多线程编程C#
点赞
收藏

51CTO技术栈公众号