Linux下线程池的实现

Linux下C++线程池的实现

关于线程池的基本概念

线程池,是一种线程的使用模式,它为了降低线程使用中频繁的创建和销毁所带来的资源消耗与代价。
通过创建一定数量的线程,让他们时刻准备就绪等待新任务的到达,而任务执行结束之后再重新回来继续待命。
这就是线程池最核心的设计思路。
相比于来一个任务创建一个线程的方式,使用线程池的优势体现在如下几点:

  1. 避免了线程的重复创建与开销带来的资源消耗代价。
  2. 提升了任务响应速度,任务来了直接选一个线程执行而无需等待线程的创建。
  3. 线程的统一分配和管理,也方便统一的监控和调优。
  4. 线程池的实现天生就实现了异步任务接口,允许你提交多个任务到线程池,线程池负责选用线程执行任务调度。

线程池的原理框图

在这里插入图片描述

  1. 管理线程主要的作用,就是在我们指定了线程池中最少线程的数量和线程池中的最大线程的数量,如果不定义线程池的管理线程,当任务过多时,线程池中的线程全部工作,任务队列会变满,导致无法继续添加任务,这个时候我们可以通过管理线程进行线程的创建。当任务计较少的时候,我们就可以不去维护那么多的线程,就可以通过管理线程,进行销毁,这就是管理线程的作用。
  2. 我们在线程池中会定义两个锁和两个条件变量,其中锁的作用,主要是锁上描述线程池的结构体和忙线程的个数,两个条件变量,主要是判断任务队列是否为空和是否为满。

线程池的实现

描述线程池的结构体

struct pthreadpool_t
{
	pthread_mutex_t lock;                 // 锁住整个结构体
	pthread_mutex_t thread_counter;       // 用于使用忙线程数时的锁
	pthread_cond_t  queue_not_full;       // 任务队列不为满 
	pthread_cond_t  queue_not_empty;      //任务队列不为空

	pthread_t* threads;					  //线程池中的线程
	pthread_t admin_tid;				  //管理线程
	pthread_task_t* task_queue;			  //任务队列

	int max_thr_num;					  //线程池中线程最大数
	int min_thr_num;					  //线程池中线程最小数
	int live_thr_num;					  //当前线程池中线程数量	 
	int wait_exit_num;					  //需要销毁的线程数
	int busy_thr_num;					  //工作线程数

	int queue_front;                      // 队头 
	int queue_rear;                       // 队尾 
	int queue_size;						  //任务数
	int queue_max_size;					  //最大任务数

	int shutdown;						  //线程池的
};

定义线程池中的线程最大数和线程最小数,来保证管理线程在创建和销毁线程时的上下限。

描述任务队列的结构体

typedef struct
{
	void* (*function)(void* arg);
	void* arg;							//任务的参数
}pthread_task_t;

我们会创建一个环形的任务队列

pool->queue_rear = (pool->queue_rear + 1) % pool->queue_max_size;
pool->queue_front = (pool->queue_front + 1) % pool->queue_max_size;

在添加任务和执行任务时,来控制队头和队尾指针的移动。

线程池的创建和初始化

pthreadpool_t* pthreadpool_create(int max_thr_num, int min_thr_num, int queue_max_size)
{
	int i;
	pthreadpool_t* pool = NULL;
	
	do
	{
		if ((pool = (pthreadpool_t*)malloc(sizeof(pthreadpool_t))) = NULL)
		{
			printf("pool malloc errno");
			break;
		}

		pool->max_thr_num = max_thr_num;
		pool->min_thr_num = min_thr_num;
		pool->queue_max_size = queue_max_size;
		pool->queue_front = 0;
		pool->queue_rear = 0;
		pool->queue_size = 0;
		pool->busy_thr_num = 0;
		pool->live_thr_num = min_thr_num;
		pool->shutdown = 0;
		pool->wait_exit_num = 0;

		pool->threads = (pthread_t*)malloc(sizeof(pthread_t) * max_thr_num);
		if (pool->threads == NULL)
		{
			printf("threads malloc errno");
			break;
		}

		pool->task_queue = (pthread_task_t*)malloc(sizeof(pthread_task_t) * queue_max_size);
		if (pool->task_queue == NULL)
		{
			printf("pool task_queue errno");
			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("mutex/cond init errno");
			break;
		}

		for (i = 0; i < min_thr_num; i++)
		{
			pthread_create(&(pool->threads[i]), NULL, pthreadpool_thread, (void*)pool);
		}
		pthread_create(&(pool->admin_tid), NULL, admin_thread, (void*)pool);

		return pool;
	} while (0);
	
	pthreadpool_free(pool);
	return NULL;
}

在这里我们主要进行线程池参数的初始化、最小线程数的线程创建、任务队列的创建和管理线程的创建(单独创建管理线程,便于管理)。
可以看到用到了do while(0)的循环,可以在任何出错的地方,直接退出,并释放线程池。

管理线程的实现

#define MIN_WAIT_TASK_NUM 10       //当任务数超过了它,就该添加新线程了
#define DEFAULT_THREAD_NUM 10      //每次创建或销毁的线程个数

void* admin_thread(void* arg)
{
	int i;
	pthreadpool_t* pool = (pthreadpool_t*)arg;
	if (pool == NULL)
	{
		printf("admimn pool errno");
	}
	while (!pool->shutdown)
	{
		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));
		printf("admin busy live -%d--%d-\n", busy_thr_num, live_thr_num);

		if (queue_size >= MIN_WAIT_TASK_NUM && live_thr_num < pool->max_thr_num)
		{
			printf("admin add-----------\n");
			pthread_mutex_lock(&(pool->lock));
			int add = 0;

			for (i = 0; i < pool->max_thr_num && add < DEFAULT_THREAD_NUM
				&& 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, pthreadpool_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)
		{

			 //一次销毁DEFAULT_THREAD_NUM个线程
			pthread_mutex_lock(&(pool->lock));
			pool->wait_exit_num = DEFAULT_THREAD_NUM;
			pthread_mutex_unlock(&(pool->lock));

			for (i = 0; i < DEFAULT_THREAD_NUM; i++)
			{
				//通知正在处于空闲的线程,自杀
				pthread_cond_signal(&(pool->queue_not_empty));
				printf("admin cler --\n");
			}
		}
	}
	return NULL;
}

我们定义了两个宏,来指定什么时候创建线程和在创建和销毁线程时的线程数量,在任务数大于MIN_WAIT_TASK_NUM的时候,就要添加线程,当工作线程乘上2的时候还小于所有的线程数时,就要销毁线程了。
销毁线程时,我们只是唤醒等待条件变量的线程,进行自杀,主要实现在工作线程的模块中,稍后再说
在对线程池结构体里的参数进行改变时,一定要加上锁!!!!!

工作线程的实现

//工作线程
void* pthreadpool_thread(void* threadpool)
{
	pthreadpool_t* pool = (pthreadpool_t*)threadpool;
	pthread_task_t task;

	while (true)
	{
		pthread_mutex_lock(&(pool->lock));
		while ((pool->queue_size == 0) && (!pool->shutdown))
		{
			printf("thread 0x%x is waiting \n", (unsigned int)pthread_self());
			pthread_cond_wait(&(pool->queue_not_empty), &(pool->lock));

			//判断是否需要清除线程,自杀功能
			if (pool->wait_exit_num > 0)
			{
				pool->wait_exit_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);//结束线程
				}
			}
		}
		//线程池开关状态
		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 + 1) % 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++;
		pthread_mutex_unlock(&(pool->thread_counter));

		(*(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--;
		pthread_mutex_unlock(&(pool->thread_counter));
	}
	return NULL;
}

在工作线程中,我们首先会等待条件变量的唤醒,如果任务队列没有任务,并且待销毁的任务大于0,那么当前线程就会被销毁,之后,就会进行任务的执行,任务执行完毕后,要通知可以添加任务的条件变量,唤醒任务任务队列不为满的条件变量,同样不要忘记在操作线程池的时候,要加上锁!!!!

添加任务的实现

//向线程池的任务队列中添加一个任务
int threadpool_add_task(pthreadpool_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));
		return -1;
	}

	/*清空工作线程的回调函数的参数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 + 1) % pool->queue_max_size; 
	pool->queue_size++;

	/*添加完任务后,队列就不为空了,唤醒线程池中的一个线程*/
	pthread_cond_signal(&(pool->queue_not_empty));
	pthread_mutex_unlock(&(pool->lock));

	return 0;
}

首先,如果任务队列为满,要等待任务队列不为满的条件变量被唤醒,才可以添加任务,操作线程池的时候,要加上锁!!!

线程池的释放

//线程池的释放
int pthreadpool_free(pthreadpool_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 1;
}

只要就是对于线程池资源的释放,new出来的空间和锁的释放。

线程池的销毁

//线程池的销毁
int pthreadpool_destroy(pthreadpool_t* pool)
{
	int i;
	if (pool == NULL)
	{
		return -1;
	}
	pool->shutdown = true;

	//销毁管理者线程
	pthread_join(pool->admin_tid, NULL);

	//通知所有线程去自杀
	for (i = 0; i < pool->live_thr_num; i++)
	{
		pthread_cond_broadcast(&(pool->queue_not_empty));
	}

	//等待线程结束 先是pthread_exit 然后等待其结束
	for (i = 0; i < pool->live_thr_num; i++)
	{
		pthread_join(pool->threads[i], NULL);
	}

	pthreadpool_free(pool);
	return 0;
}

首先销毁管理线程,之后让线程退出,之后等待线程的结束。

在这里在整理一下线程池的创建过程,首先创建指定的线程数,等待任务队列有任务,通过条件变量来判断任务队列是否为满和为空,之后开始执行,管理线程主要进行线程的创建和销毁,其实在创建线程池的时候,最主要的就是锁的使用,要注意锁住的代码片段的大小。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值