/*
线程池组成:
1、管理者线程:创建并管理线程,包括添加、删除、销毁线程,添加新任务
2、工作线程:线程池中的线程,执行管理者分配的任务
3、任务接口:任务要实现的接口,供工作线程调用
4、任务队列:存放没有处理的任务,缓冲作用
*/
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include "threadpool.h" #define DEFAULT_TIME 10 /*10s检测一次*/
#define MIN_WAIT_TASK_NUM 10 /*如果queue_size > MIN_WAIT_TASK_NUM 添加新的线程到线程池*/
#define DEFAULT_THREAD_VARY 10 /*每次创建和销毁线程的个数*/
#define true 1
#define false 0 //任务接口
typedef struct {
void *(*function)(void *); /* 函数指针,回调函数 */
void *arg; /* 上面函数的参数 */
} threadpool_task_t; /* 各子线程任务结构体 */ /* 描述线程池相关信息 */
struct threadpool_t {
pthread_mutex_t lock; /* 用于锁住本结构体 */
pthread_mutex_t thread_counter; /* 记录忙状态线程个数de琐 -- busy_thr_num */
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; /* 标志位,线程池使用状态,true或false */
}; /**
* @function void *threadpool_thread(void *threadpool)
* @desc the worker thread
* @param threadpool the pool which own the thread
*/
void *threadpool_thread(void *threadpool); /**
* @function void *adjust_thread(void *threadpool);
* @desc manager thread
* @param threadpool the threadpool
*/
void *adjust_thread(void *threadpool); /**
* check a thread is alive
*/
int is_thread_alive(pthread_t tid);
int threadpool_free(threadpool_t *pool); //创建线程池
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;/*跳出do while*/
} pool->min_thr_num = min_thr_num;
pool->max_thr_num = max_thr_num;
pool->busy_thr_num = ;
pool->live_thr_num = min_thr_num; /* 活着的线程数 初值=最小线程数 */
pool->queue_size = ; /* 有0个产品 */
pool->queue_max_size = queue_max_size;
pool->queue_front = ;
pool->queue_rear = ;
pool->shutdown = false; /* 不关闭线程池 */ /* 根据最大线程上限数, 给工作线程数组开辟空间, 并清零 */
pool->threads = (pthread_t *)malloc(sizeof(pthread_t)*max_thr_num);
if (pool->threads == NULL) {
printf("malloc threads fail");
break;
}
memset(pool->threads, , 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("malloc task_queue fail");
break;
} /* 初始化互斥琐、条件变量 */
if (pthread_mutex_init(&(pool->lock), NULL) !=
|| pthread_mutex_init(&(pool->thread_counter), NULL) !=
|| pthread_cond_init(&(pool->queue_not_empty), NULL) !=
|| pthread_cond_init(&(pool->queue_not_full), NULL) != )
{
printf("init the lock or cond fail");
break;
} /* 启动 min_thr_num 个 work thread */
for (i = ; i < min_thr_num; i++) {
pthread_create(&(pool->threads[i]), NULL, threadpool_thread, (void *)pool);/*pool指向当前线程池*/
printf("start thread 0x%x...\n", (unsigned int)pool->threads[i]);
}
pthread_create(&(pool->adjust_tid), NULL, adjust_thread, (void *)pool);/* 启动管理者线程 */ return pool; } while (); threadpool_free(pool); /* 前面代码调用失败时,释放poll存储空间 */ return NULL;
} /* 向线程池中 添加一个任务 */
int threadpool_add(threadpool_t *pool, void*(*function)(void *arg), void *arg)
{
pthread_mutex_lock(&(pool->lock)); /* ==为真,队列已经满, 调wait阻塞 */
while ((pool->queue_size == pool->queue_max_size) && (!pool->shutdown)) {
pthread_cond_wait(&(pool->queue_not_full), &(pool->lock));
}
if (pool->shutdown) {
pthread_mutex_unlock(&(pool->lock));
} /* 清空 工作线程 调用的回调函数 的参数arg */
if (pool->task_queue[pool->queue_rear].arg != NULL) {
free(pool->task_queue[pool->queue_rear].arg);
pool->task_queue[pool->queue_rear].arg = NULL;
}
/*添加任务到任务队列里*/
pool->task_queue[pool->queue_rear].function = function;
pool->task_queue[pool->queue_rear].arg = arg;
pool->queue_rear = (pool->queue_rear + ) % pool->queue_max_size; /* 队尾指针移动, 模拟环形 */
pool->queue_size++; /*添加完任务后,队列不为空,唤醒线程池中 等待处理任务的线程*/
//生产者消费者模型

pthread_cond_signal(&(pool->queue_not_empty));
pthread_mutex_unlock(&(pool->lock)); return ;
} /* 线程池中各个工作线程 */
void *threadpool_thread(void *
threadpool)
{
threadpool_t *pool = (threadpool_t *)threadpool;
threadpool_task_t task; while (true) {
/* Lock must be taken to wait on conditional variable */
/*刚创建出线程,等待任务队列里有任务,否则阻塞等待任务队列里有任务后再唤醒接收任务*/
pthread_mutex_lock(&(pool->lock)); /*queue_size == 0 说明没有任务,调 wait 阻塞在条件变量上, 若有任务,跳过该while*/
while ((pool->queue_size == ) && (!pool->shutdown)) {
printf("thread 0x%x is waiting\n", (unsigned int)pthread_self());
pthread_cond_wait(&(pool->queue_not_empty), &(pool->lock)); /*清除指定数目的空闲线程,如果要结束的线程个数大于0,结束线程*/
if (pool->wait_exit_thr_num > ) {
pool->wait_exit_thr_num--; /*如果线程池里线程个数大于最小值时可以结束当前线程*/
if (pool->live_thr_num > pool->min_thr_num) {
printf("thread 0x%x is exiting\n", (unsigned int)pthread_self());
pool->live_thr_num--;
pthread_mutex_unlock(&(pool->lock));
pthread_exit(NULL);
}
}
} /*如果指定了true,要关闭线程池里的每个线程,自行退出处理*/
if (pool->shutdown) {
pthread_mutex_unlock(&(pool->lock));
printf("thread 0x%x is exiting\n", (unsigned int)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 + ) % pool->queue_max_size; /* 出队,模拟环形队列 */
pool->queue_size--; /*通知可以有新的任务添加进来*/
pthread_cond_broadcast(&(pool->queue_not_full)); /*任务取出后,立即将 线程池琐 释放*/
pthread_mutex_unlock(&(pool->lock)); /*执行任务*/
printf("thread 0x%x start working\n", (unsigned int)pthread_self());
pthread_mutex_lock(&(pool->thread_counter)); /*忙状态线程数变量琐*/
pool->busy_thr_num++; /*忙状态线程数+1*/
pthread_mutex_unlock(&(pool->thread_counter));
(*(task.function))(task.arg); /*执行回调函数任务*/
//task.function(task.arg); /*执行回调函数任务*/ /*任务结束处理*/
printf("thread 0x%x end working\n", (unsigned int)pthread_self());
pthread_mutex_lock(&(pool->thread_counter));
pool->busy_thr_num--; /*处理掉一个任务,忙状态数线程数-1*/
pthread_mutex_unlock(&(pool->thread_counter));
} pthread_exit(NULL);
} /* 管理线程 */
void *adjust_thread(void *
threadpool)
{
int i;
threadpool_t *pool = (threadpool_t *)threadpool;
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)); /* 创建新线程 算法: 任务数大于最小线程池个数, 且存活的线程数少于最大线程个数时 如:30>=10 && 40<100*/
if (queue_size >= MIN_WAIT_TASK_NUM && live_thr_num < pool->max_thr_num) {
pthread_mutex_lock(&(pool->lock));
int add = ; /*一次增加 DEFAULT_THREAD 个线程*/
for (i = ; i < pool->max_thr_num && add < DEFAULT_THREAD_VARY
&& pool->live_thr_num < pool->max_thr_num; i++) {
if (pool->threads[i] == || !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));
} /* 销毁多余的空闲线程 算法:忙线程X2 小于 存活的线程数 且 存活的线程数 大于 最小线程数时*/
if ((busy_thr_num * ) < live_thr_num && live_thr_num > pool->min_thr_num) { /* 一次销毁DEFAULT_THREAD个线程, 隨機10個即可 */
pthread_mutex_lock(&(pool->lock));
pool->wait_exit_thr_num = DEFAULT_THREAD_VARY; /* 要销毁的线程数 设置为10 */
pthread_mutex_unlock(&(pool->lock)); for (i = ; i < DEFAULT_THREAD_VARY; i++) {
/* 通知处在空闲状态的线程, 他们会自行终止*/
pthread_cond_signal(&(pool->queue_not_empty));
}
}
} return NULL;
} //销毁线程:先销毁管理线程,防止添加任务等情况
int threadpool_destroy(threadpool_t *pool)
{
int i;
if (pool == NULL) {
return -;
}
pool->shutdown = true; /*先销毁管理线程*/
pthread_join(pool->adjust_tid, NULL); for (i = ; i < pool->live_thr_num; i++) {
/*通知所有的空闲线程*/
pthread_cond_broadcast(&(pool->queue_not_empty));
}
for (i = ; i < pool->live_thr_num; i++) {
pthread_join(pool->threads[i], NULL);
}
threadpool_free(pool); return ;
} int threadpool_free(threadpool_t *pool)
{
if (pool == NULL) {
return -;
} 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 ;
} int threadpool_all_threadnum(threadpool_t *pool)
{
int all_threadnum = -;
pthread_mutex_lock(&(pool->lock));
all_threadnum = pool->live_thr_num;
pthread_mutex_unlock(&(pool->lock));
return all_threadnum;
} int threadpool_busy_threadnum(threadpool_t *pool)
{
int busy_threadnum = -;
pthread_mutex_lock(&(pool->thread_counter));
busy_threadnum = pool->busy_thr_num;
pthread_mutex_unlock(&(pool->thread_counter));
return busy_threadnum;
} int is_thread_alive(pthread_t tid)
{
int kill_rc = pthread_kill(tid, ); //发0号信号,测试线程是否存活
if (kill_rc == ESRCH) {
return false;
} return true;
} /*测试*/ #if 1
/* 线程池中的线程,模拟处理业务 */
void *process(void *arg)
{
printf("thread 0x%x working on task %d\n ",(unsigned int)pthread_self(),*(int *)arg);
sleep();
printf("task %d is end\n",*(int *)arg); return NULL;
}
int main(void)
{
/*threadpool_t *threadpool_create(int min_thr_num, int max_thr_num, int queue_max_size);*/ threadpool_t *thp = threadpool_create(,,);/*创建线程池,池里最小3个线程,最大100,队列最大100*/
printf("pool inited"); //int *num = (int *)malloc(sizeof(int)*20);
int num[], i;
for (i = ; i < ; i++) {
num[i]=i;
printf("add task %d\n",i);
threadpool_add(thp, process, (void*)&num[i]); /* 向线程池中添加任务 */
}
sleep(); /* 等子线程完成任务 */
threadpool_destroy(thp); return ;
} #endif

C,线程池的更多相关文章

  1. 多线程爬坑之路-学习多线程需要来了解哪些东西?(concurrent并发包的数据结构和线程池,Locks锁,Atomic原子类)

    前言:刚学习了一段机器学习,最近需要重构一个java项目,又赶过来看java.大多是线程代码,没办法,那时候总觉得多线程是个很难的部分很少用到,所以一直没下决定去啃,那些年留下的坑,总是得自己跳进去填 ...

  2. C#多线程之线程池篇3

    在上一篇C#多线程之线程池篇2中,我们主要学习了线程池和并行度以及如何实现取消选项的相关知识.在这一篇中,我们主要学习如何使用等待句柄和超时.使用计时器和使用BackgroundWorker组件的相关 ...

  3. C#多线程之线程池篇2

    在上一篇C#多线程之线程池篇1中,我们主要学习了如何在线程池中调用委托以及如何在线程池中执行异步操作,在这篇中,我们将学习线程池和并行度.实现取消选项的相关知识. 三.线程池和并行度 在这一小节中,我 ...

  4. C#多线程之线程池篇1

    在C#多线程之线程池篇中,我们将学习多线程访问共享资源的一些通用的技术,我们将学习到以下知识点: 在线程池中调用委托 在线程池中执行异步操作 线程池和并行度 实现取消选项 使用等待句柄和超时 使用计时 ...

  5. NGINX引入线程池 性能提升9倍

    1. 引言 正如我们所知,NGINX采用了异步.事件驱动的方法来处理连接.这种处理方式无需(像使用传统架构的服务器一样)为每个请求创建额外的专用进程或者线程,而是在一个工作进程中处理多个连接和请求.为 ...

  6. Java线程池解析

    Java的一大优势是能完成多线程任务,对线程的封装和调度非常好,那么它又是如何实现的呢? jdk的包下和线程相关类的类图. 从上面可以看出Java的线程池主的实现类主要有两个类ThreadPoolEx ...

  7. Android线程管理之ExecutorService线程池

    前言: 上篇学习了线程Thread的使用,今天来学习一下线程池ExecutorService. 线程管理相关文章地址: Android线程管理之Thread使用总结 Android线程管理之Execu ...

  8. Android线程管理之ThreadPoolExecutor自定义线程池

    前言: 上篇主要介绍了使用线程池的好处以及ExecutorService接口,然后学习了通过Executors工厂类生成满足不同需求的简单线程池,但是有时候我们需要相对复杂的线程池的时候就需要我们自己 ...

  9. -Android -线程池 批量上传图片 -附php接收代码

    (出处:http://www.cnblogs.com/linguanh/) 目录: 1,前序 2,类特点 3,用法 4,java代码 5,php代码 1,前序 还是源于重构,看着之前为赶时间写着的碎片 ...

  10. C#多线程--线程池(ThreadPool)

    先引入一下线程池的概念: 百度百科:线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务.线程池线程都是后台线程.每个线程都使用默认的堆栈大小,以默认的优先级运行, ...

随机推荐

  1. django+uwsgi+nginx: websock 报502/400

    耽搁了近2个月,终于解决了,主要是nginx/uwsgi/django相关的配置: 一.django工程settings.py,添加 WEBSOCKET_FACTORY_CLASS = "d ...

  2. Windows 编程 键盘

    键盘对于大家来说可能再也熟悉不过了,它和鼠标是现在最常用的电脑输入设备.虽然在现在的图形界面操作系统下使用鼠标比使用键盘更方便.更广泛,但是鼠标还是一时半会儿取代不了它的老前辈——键盘的地位,尤其是在 ...

  3. Linux I2C核心、总线和设备驱动

    目录 更新记录 一.Linux I2C 体系结构 1.1 Linux I2C 体系结构的组成部分 1.2 内核源码文件 1.3 重要的数据结构 二.Linux I2C 核心 2.1 流程 2.2 主要 ...

  4. js中数组方法及分类

    数组的方法有很多,这里简单整理下常用的21种方法,并且根据它们的作用分了类,便于记忆和理解. 根据是否改变原数组,可以分为两大类,两大类又根据不同功能分为几个小类 一.操作使原数组改变   1.数组的 ...

  5. AJAX中所谓的异步

    async javascript and xml 异步的js和xml 在AJAX中的异步不是我们所理解的同步异步编程,而泛指“局部刷新”,但是我们以后的AJAX请求尽可能异步请求数据(因为异步数据获取 ...

  6. wpf win10 popup位置偏移问题

    同样问题参照: https://stackoverflow.com/questions/18113597/wpf-handedness-with-popups 解决方案: private static ...

  7. C++手动调用析构函数无效问题排查

    在学习C++的时候,都知道不要手动调用析构函数,也不要在构造函数.析构函数里调用虚函数.工作这么多年,这些冷门的知识极少用到,渐渐被繁杂的业务逻辑淹没掉. 不过,最近项目里出现了析构函数没有被正确地调 ...

  8. Oracle权限管理详解(2)

    详见:https://blog.csdn.net/u013412772/article/details/52733050 Oracle数据库推荐以引用博客: http: http:.html http ...

  9. redis----Not only Sql 理论

    数据存储的瓶颈:(mysql ==>500万数据就已经很慢了) 1 数据量的总大小,一个机器放不下时 2 数据 的索引,一个机器的内存放不下时 3 访问量(读写混合),一个实例不能承受 Redi ...

  10. 学习笔记:安装swig+用SWIG封装C++为Python模块+SWIG使用说明

    这段时间一直在摸索swing,用它来封装C++代码来生成python脚步语言.并总结了swing从安装到配置再到代码封装编译生成动态库的整个过程,下面这篇文章都是我在实际的运用中的一些经验总结,分享给 ...