线程池(linux)

线程池

概念

线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务。线程池线程都是后台线程。每个线程都使用默认的堆栈大小,以默认的优先级运行,并处于多线程单元中。我们将任务添加到任务队列中,线程池得知有任务到来后,会唤醒线程,如若所有线程都在执行任务,则线程会处理完当前任务后,在处理任务队列中的线程。

作用

线程池可以节省我们的系统资源和时间
线程过多会带来调度开销,进而影响缓存局部性和整体性能。而线程池维护着多个线程,等待着监督管理者分配可并发执行的任务。这避免了在处理短时间任务时创建与销毁线程的代价。线程池不仅能够保证内核的充分利用,还能防止过分调度。可用线程数量应该取决于可用的并发处理器、处理器内核、内存、网络sockets等的数量。

在创建线程池时,创建的数量也很有讲究,我们不能创建的太多,会导致很多线程根本用不到而导致系统资源的浪费。创建的太少呢就会导致线程池过度繁忙,使任务不能及时的得到解决,导致任务冗杂,效率太低。

下面我们贴代码详细讲解

/*任务结构*/  
typedef struct worker
{
	void (*process)(char *str, int socket);  // 回调函数 
	
	/* 任务中的数据 我们用字符串和socket来讲解(根据实际情况可自行更换任务数据)*/
	char str[200]; 
	int socket;

	struct worker *next;                      
}create_worker;
/*线程池结构*/
typedef struct
{
	pthread_mutex_t queue_mutex;  //线程锁
	
	pthread_cond_t queue_cond;	  //条件变量
	
	/*链表结构,线程池中有所等待任务*/
	create_worker *queue_head;
	
	/*是否销毁线程池*/
	int shutdown;
	pthread_t *threadid; //在此处使用指针结构是我们根据需求创造不同的线程数量,可以进行动态分配
	
	/*线程池中允许的活动线程数目*/
	int max_thread_num;
	
	/*当前等待队列的任务数目*/
	int cur_queue_size;
}create_pool;


static create_pool *pool = NULL; //我们使用静态变量 全局可见

/*创建线程池*/
void pool_init(int max_thread_num)
{
	pool = (create_pool *)malloc(sizeof(create_pool)); // 构造线程池
	
	pthread_mutex_init(&(pool->queue_mutex), NULL);    //初始化锁
	
	pthread_cond_init(&(pool->queue_cond), NULL);      //初始化条件变量
	
	pool->queue_head = NULL;    //任务为空
	
	pool->max_thread_num = max_thread_num; //线程数量
	
	pool->cur_queue_size = 0;  //任务数量
	
	pool->shutdown = 0;
	
	/* 初始化线程池中的线程*/
	pool->threadid = (pthread_t *)malloc(sizeof(pthread_t) * max_thread_num);
	for(int i = 0; i < max_thread_num; i++)
	{
		pthread_create(&pool->threadid[i], NULL, thread_routine, NULL);
	}
}

/*向线程池中加入任务*/
void pool_add_worker(void (*process) (char *str, int socket), char *str, int socket)
{
	/*构建一个新任务*/
	create_worker *newworker = (create_worker*)malloc(sizeof(create_worker));
	
	newworker->process = process; //给新任务的回调函数赋值

	/* 任务中的数据进行赋值*/  
	memcpy(newworker->str, str, 200);
	newworker->socket = socket;
	newworker->next = NULL;
	
	pthread_mutex_lock(&pool->queue_mutex); //此处上锁 作用 需要将任务添加到任务队列中,需要用的共用变量size,若不锁住保证安全,则任务数量会造成混乱,导致线程池不能正常工作。 
	
	/*将任务加入到等待队列*/
	create_worker *member = pool->queue_head;
	if(member != NULL)
	{
		while(member->next != NULL)
			member = member->next;
		member->next = newworker;
	}
	else
		pool->queue_head = newworker;
		
	assert(pool->queue_head != NULL);
	pool->cur_queue_size++;  //将任务数量+1

	pthread_mutex_unlock(&pool->queue_mutex); //解锁
	
	/*等待队列有任务,唤醒一个等待的线程*/
	pthread_cond_signal(&pool->queue_cond);
}
/*销毁线程池, 等待队列中的任务不会在执行,但是正在运行的线程一定会把任务运行完后在退出*/
int pool_destroy()
{
	if(pool->shutdown)
		return -1;		//防止两次调用	
	pool->shutdown = 1;
	/*唤醒所有的等待线程,线程池要销毁了*/
	pthread_cond_broadcast(&pool->queue_cond);

	/*阻塞等待线程退出,否则就成僵尸了*/
	for(int i = 0; i < pool->max_thread_num; i++)
		pthread_join(pool->threadid[i], NULL);      //等待所有线程执行完毕再销毁
	free(pool->threadid);
	/*销毁等待队列*/
	create_worker *head = NULL;
	while(pool->queue_head != NULL)
	{
		head = pool->queue_head;
		pool->queue_head = pool->queue_head->next;
		free(head);
	}

	/*销毁条件变量和互斥量*/
	pthread_mutex_destroy(&pool->queue_mutex);
	pthread_cond_destroy(&pool->queue_cond);
	free(pool);
	pool = NULL;
}

void *thread_routine(void *arg)
{
	while(1)
	{
		pthread_mutex_lock(&pool->queue_mutex);
		/*如果等待队列为0并且不销毁线程池,则处于阻塞状态*/
		while(pool->cur_queue_size == 0 && !pool->shutdown)
		{
			printf("thread: %ld is wait\n", pthread_self());
			pthread_cond_wait(&pool->queue_cond, &pool->queue_mutex); //让线程挂起等待,然后将锁释放掉,最终将线程池中所有线程都挂起,并在此阻塞住。
		}
		
		/*线程池要销毁了*/
		if(pool->shutdown)
		{
			/*遇到break, continue, return 等跳转语句,要记得先解锁*/
			pthread_mutex_unlock(&pool->queue_mutex);
			printf("thread %ld will exit\n", pthread_self());
			pthread_exit(NULL);
		}
		//pthread_cond_wait()函数被唤醒后,锁会被重新锁住。
		//执行到这段代码证明有线程被唤醒工作,我们打印线程id,此处相当于调试信息
		printf("thread %ld is starting to work\n", pthread_self());
		
		assert(pool->cur_queue_size != 0);
		assert(pool->queue_head != NULL);
		
		/*等待队列长度减1,并去除链表中的头元素*/
		pool->cur_queue_size--;
		create_worker *work = pool->queue_head;
		pool->queue_head = work->next;
		pthread_mutex_unlock(&pool->queue_mutex); //在此处解锁是因为我们的共用变量size被赋值完成,任务和队列也已更新,在此处解锁。

		/*调用回调函数,执行任务*/
		(work->process) (work->str, work->socket);
		free(work);
		work = NULL;
	}
}

/*回调函数*/
void process(char *str, int socket)
{
	此处写实现任务需要的代码
}

上述线程池用于我的聊天室项目点我感兴趣的可以看一下,大家可以一起交流。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章