Linux系统编程(十)线程池
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <signal.h>
#include <errno.h> #define DEFAULT_TIME 10
#define DEFAULT_THREAD_VARY 10
#define MIN_WAIT_TASK_NUM 10
typedef struct threadpool_task {
void *(*function)(void *);
void *arg;
} threadpool_task_t; typedef struct threadpool {
pthread_mutex_t lock; // 锁住本结构体
pthread_mutex_t thread_counter; // 记录忙状态线程个数的锁 pthread_cond_t queue_not_full; // 任务队列满时,添加任务的线程阻塞,等待此条件变量
pthread_cond_t queue_not_empty; // 任务队列不为空,通知等待任务的线程 pthread_t *threads; // 存放线程池中的线程号tid
pthread_t adjust_tid; // 存管理线程tid
threadpool_task_t *task_queue; // 任务队列数组 int min_thr_num; // 线程池最小线程数
int max_thr_num; // 线程池最大线程数
int live_thr_num; // 当前存活线程数
int busy_thr_num; // 忙状态线程个数
int wait_exit_thr_num; // 要销毁的线程个数 int queue_front; // task_queue队头下标
int queue_rear; // task_queue队尾下标
int queue_size; // task_queue队中实际任务数
int queue_max_size; // task_queue队列可容纳任务数量上限 int shutdown; // 线程池使用状态
} threadpool_t; int is_thread_alive(pthread_t tid)
{
int kill_rc = pthread_kill(tid, 0);
if(kill_rc == ESRCH)
return 0;
else
return -1;
} int threadpool_free(threadpool_t *pool)
{
if(pool == NULL)
return -1; if(pool->task_queue)
free(pool->task_queue); if(pool->threads)
{
free(pool->threads);
pthread_mutex_lock(&(pool->lock));
pthread_mutex_destroy(&(pool->lock));
pthread_mutex_lock(&(pool->thread_counter));
pthread_mutex_destroy(&(pool->thread_counter));
pthread_cond_destroy(&(pool->queue_not_empty));
pthread_cond_destroy(&(pool->queue_not_full));
}
free(pool);
pool = NULL; return 0;
} int threadpool_destory(threadpool_t *pool)
{
int i;
if(pool == NULL)
return -1; pool->shutdown = 1; pthread_join(pool->adjust_tid, NULL); for(i = 0; i < pool->live_thr_num; i++)
pthread_cond_broadcast(&(pool->queue_not_empty)); for(i = 0; i < pool->live_thr_num; i++)
pthread_join(pool->threads[i], NULL); threadpool_free(pool); return 0;
} void *threadpool_thread(void *threadpool)
{
threadpool_t *pool = (threadpool_t *)threadpool;
threadpool_task_t task; while(1)
{
pthread_mutex_lock(&(pool->lock)); while((pool->queue_size == 0) && (!pool->shutdown)){
printf("thread 0x%lx is waiting\n", pthread_self());
pthread_cond_wait(&(pool->queue_not_empty), &(pool->lock)); if(pool->wait_exit_thr_num > 0){
pool->wait_exit_thr_num--; if(pool->live_thr_num > pool->min_thr_num){
printf("thread 0x%lx is exsiting\n", pthread_self());
pool->live_thr_num--;
pthread_mutex_unlock(&(pool->lock));
pthread_exit(NULL);
} }
} if(pool->shutdown){
pthread_mutex_unlock(&(pool->lock));
printf("thread 0x%lx is existing\n", pthread_self());
pthread_detach(pthread_self());
pthread_exit(NULL);
} task.function = pool->task_queue[pool->queue_front].function;
task.arg = pool->task_queue[pool->queue_front].arg; pool->queue_front = (pool->queue_front + 1) % pool->queue_max_size;
pool->queue_size--; pthread_cond_broadcast(&(pool->queue_not_full)); pthread_mutex_unlock(&(pool->lock)); printf("thread 0x%lx start working\n", pthread_self()); (*(task.function))(task.arg); printf("thread 0x%lx end working\n", pthread_self());
pthread_mutex_lock(&(pool->thread_counter));
pool->busy_thr_num--;
pthread_mutex_unlock(&(pool->thread_counter));
} pthread_exit(NULL);
} void *adjust_thread(void *threadpool)
{
threadpool_t *pool = (threadpool_t *)threadpool;
int i;
while(!pool->shutdown) { sleep(DEFAULT_TIME); pthread_mutex_lock(&(pool->lock));
int queue_size = pool->queue_size;
int live_thr_num = pool->live_thr_num;
pthread_mutex_unlock(&(pool->lock)); pthread_mutex_lock(&(pool->thread_counter));
int busy_thr_num = pool->busy_thr_num;
pthread_mutex_unlock(&(pool->thread_counter)); if(queue_size >= MIN_WAIT_TASK_NUM && live_thr_num < pool->max_thr_num)
{
pthread_mutex_lock(&(pool->lock));
int add = 0; for(i = 0; i < pool->max_thr_num && add < DEFAULT_THREAD_VARY &&
pool->live_thr_num < pool->max_thr_num; i++) {
if(pool->threads[i] == 0 || !is_thread_alive(pool->threads[i])) {
pthread_create(&(pool->threads[i]), NULL, threadpool_thread, (void*)pool);
add++;
pool->live_thr_num++;
}
}
pthread_mutex_unlock(&(pool->lock));
} if((busy_thr_num *2) < live_thr_num && live_thr_num > pool->min_thr_num){
pthread_mutex_lock(&(pool->lock));
pool->wait_exit_thr_num = DEFAULT_THREAD_VARY;
pthread_mutex_unlock(&(pool->lock)); for(i = 0; i < DEFAULT_THREAD_VARY; i++){
pthread_cond_signal(&(pool->queue_not_empty));
}
}
}
return NULL;
} threadpool_t *threadpool_create(int min_thr_num, int max_thr_num, int queue_max_size)
{
int i;
threadpool_t *pool = NULL;
do{
if((pool = (threadpool_t *)malloc(sizeof(threadpool_t))) == NULL){
printf("malloc threadpool fail");
break;
} pool->min_thr_num = min_thr_num;
pool->max_thr_num = max_thr_num;
pool->busy_thr_num = 0;
pool->live_thr_num = min_thr_num;
pool->queue_size = 0;
pool->queue_max_size = queue_max_size;
pool->queue_front = 0;
pool->queue_rear = 0;
pool->shutdown = 0; pool->threads = (pthread_t *)malloc(sizeof(pthread_t)*max_thr_num);
if(pool->threads == NULL)
{
printf("malloc threads fail\n");
break;
}
memset(pool->threads, 0, sizeof(pthread_t)*max_thr_num); pool->task_queue = (threadpool_task_t*)malloc(sizeof(threadpool_task_t)*queue_max_size);
if(pool->task_queue == NULL)
{
printf("mallc task_queue fail\n");
break;
} if(pthread_mutex_init(&(pool->lock), NULL) != 0
|| pthread_mutex_init(&(pool->thread_counter), NULL) != 0
|| pthread_cond_init(&(pool->queue_not_empty), NULL) != 0
|| pthread_cond_init(&(pool->queue_not_full), NULL) != 0 )
{
printf("init mutex or cond fail\n");
break;
} for(i = 0; i < min_thr_num; i++)
{
pthread_create(&(pool->threads[i]), NULL, threadpool_thread, (void*)pool);
printf("start thread 0x%lx...\n", pool->threads[i]);
} pthread_create(&(pool->adjust_tid), NULL, adjust_thread, (void*)pool); return pool; }while(0); threadpool_free(pool); return NULL;
} void threadpool_add(threadpool_t *pool, void *(*func)(void*arg), void *arg)
{
pthread_mutex_lock(&(pool->lock)); // fang zhi qiang suo
while((pool->queue_size == pool->queue_max_size) && (!pool->shutdown))
pthread_cond_wait(&(pool->queue_not_full), &(pool->lock)); if(pool->shutdown){
pthread_cond_broadcast(&(pool->queue_not_empty));
pthread_mutex_unlock(&(pool->lock));
} if(pool->task_queue[pool->queue_rear].arg != NULL)
pool->task_queue[pool->queue_rear].arg = NULL; pool->task_queue[pool->queue_rear].function = func;
pool->task_queue[pool->queue_rear].arg = arg;
pool->queue_rear = (pool->queue_rear + 1) % pool->queue_max_size;
pool->queue_size++; pthread_cond_signal(&(pool->queue_not_empty));
pthread_mutex_unlock(&(pool->lock)); } void *process(void *arg)
{
printf("thread 0x%lx working on task %p\n", pthread_self(), arg);
sleep(1);
printf("task %p is end\n", arg);
return NULL;
} int main(int argc, char** argv)
{
threadpool_t *thp = threadpool_create(3, 100, 100); int num[20];
for(int i = 0; i < 20; i++)
{
num[i] = i;
threadpool_add(thp, process, (void*)&num[i]); }
sleep(10);
threadpool_destory(thp); return 0;
}
Linux系统编程(十)线程池的更多相关文章
- linux系统编程:线程原语
线程原语 线程概念 线程(thread),有时被称为轻量级进程(Lightweight Process,LWP).是程序运行流的最小单元.一个标准的线程由线程ID.当前指令指针(PC),寄存器集合和堆 ...
- Linux系统编程:线程控制
一.提出问题 问1.线程存在的意义是什么?什么时候适合使用多线程? 答1.在单进程环境中实现多任务,线程可访问其所在进程的资源,例如内存.描述符等.对于单进程,如果要完成多项任务,这些任务只能依次执行 ...
- linux系统编程:线程同步-相互排斥量(mutex)
线程同步-相互排斥量(mutex) 线程同步 多个线程同一时候訪问共享数据时可能会冲突,于是须要实现线程同步. 一个线程冲突的演示样例 #include <stdio.h> #includ ...
- linux系统编程:线程同步-信号量(semaphore)
线程同步-信号量(semaphore) 生产者与消费者问题再思考 在实际生活中,仅仅要有商品.消费者就能够消费,这没问题. 但生产者的生产并非无限的.比如,仓库是有限的,原材料是有限的,生产指标受消费 ...
- 《Unix/Linux系统编程》第十周学习笔记
<Unix/Linux系统编程>第十周学习笔记 块设备I/O和缓冲区管理 解释块设备I/O的原理和I/O缓冲的优点 I/O缓冲区:内核中的一系列NBUF缓冲区用作缓冲区缓存.每个缓冲区用一 ...
- Linux系统编程——线程私有数据
在多线程程序中.常常要用全局变量来实现多个函数间的数据共享.因为数据空间是共享的,因此全局变量也为全部线程共同拥有. 測试代码例如以下: #include <stdio.h> #inclu ...
- Linux 系统编程 学习:09-线程:线程的创建、回收与取消
Linux 系统编程 学习:09-线程:线程的创建.回收与取消 背景 我们在此之前完成了 有关进程的学习.从这一讲开始我们学习线程. 完全的开发可以参考:<多线程编程指南> 在Linux ...
- Linux 系统编程 学习:10-线程:线程的属性
Linux 系统编程 学习:10-线程:线程的属性 背景 上一讲我们介绍了线程的创建,回收与销毁:简单地提到了线程属性.这一讲我们就来具体看看,线程的属性. 概述 #include <pthre ...
- Linux 系统编程 学习:11-线程:线程同步
Linux 系统编程 学习:11-线程:线程同步 背景 上一讲 我们介绍了线程的属性 有关设置.这一讲我们来看线程之间是如何同步的. 额外安装有关的man手册: sudo apt-get instal ...
- 《Unix/Linux系统编程》第十二周学习笔记
<Unix/Linux系统编程>第十二周学习笔记 MySQL数据库简介 MySQL是一个关系型数据库管理系统,是最流行的关系型数据库管理系统之一.在 WEB 应用方面,MySQL 是最好的 ...
随机推荐
- 前端使用 Konva 实现可视化设计器(4)
给上一章做一个补充,就是实现通过上下左右按键移动所选节点. 继续求 Star ,希望大家多多一键三连,十分感谢大家的支持~ 创作不易,Star 50 个,创作加速! github源码 gitee源码 ...
- Spring Cloud Alibaba 致力于提供微服务开发的一站式解决方案。此项目包含开发分布式应用服务的必需组件-Nacos 、Sentinel等
概述 Spring Cloud Alibaba 致力于提供微服务开发的一站式解决方案.此项目包含开发分布式应用服务的必需组件. 方便开发者通过 Spring Cloud 编程模型轻松使用这些组件来开发 ...
- xml转voc,voc转coco,coco转yolo,coco划分,coco检查,yolo检查,coco可视化
平常用coco格式的数据集比较多,所有这里整合一下数据集相关的常用的脚本. pycocotools安装 这个非常重要,因为处理coco数据集时,用pycocotools包非常方便. 自行搜索一下怎么安 ...
- leetcode每日一题:836. 矩形重叠
836. 矩形重叠 矩形以列表 [x1, y1, x2, y2] 的形式表示,其中 (x1, y1) 为左下角的坐标,(x2, y2) 是右上角的坐标. 如果相交的面积为正,则称两矩形重叠.需要明确的 ...
- Java面试题:请谈谈对ThreadLocal的理解?
ThreadLocal是一种特殊的变量存储机制,它提供了一种方式,可以在每个线程中保存数据,而不会受到其他线程的影响.这种机制在多线程编程中非常有用,因为它允许每个线程拥有自己的数据副本,从而避免了数 ...
- Dataphin产品核心功能大图(六)发布中心:生产和开发隔离模式下的保护伞
简介:Dataphin,用中台方法论打造企业级好数据.Dataphin是阿里巴巴集团OneData数据治理方法论内部实践的云化输出,一站式提供数据采.建.管.用全生命周期的大数据能力,以助力企业显著 ...
- OpenYurt 联手 eKuiper,解决 IoT 场景下边缘流数据处理难题
简介: 云计算的出现促使物联网实现爆炸式增长.在设备规模和业务复杂度不断攀升的趋势之下,边缘计算因其能够将计算能力更靠近网络边缘和设备,从而带来云性能成本的降低,也在这波浪潮之下得到快速发展. 作者 ...
- 技术干货|基于Apache Hudi 的CDC数据入湖「内附干货PPT下载渠道」
简介: 阿里云技术专家李少锋(风泽)在Apache Hudi 与 Apache Pulsar 联合 Meetup 杭州站上的演讲整理稿件,本议题将介绍典型 CDC 入湖场景,以及如何使用 Pulsa ...
- [FAQ] Fontconfig error: Cannot load default config file
在使用一些第三方库时(比如生成图片),如果出现此提示,说明系统里缺少字体. 在 Ubuntu 上可以运行:$ apt-get install fontconfig 在 Centos 上可以运行:$ ...
- [FAQ] JS 时间戳格式化为 date
拷贝使用,不用引入第三方库 function formatDate (date = 0, fmt = 'yyyy-MM-dd hh:mm:ss') { date = new Date(+date) i ...