线程池C语言实现

一、线程池C语言实现

/*
 * ThreadPool.c
 *
 *  Created on: 2021年4月30日
 *      Author: zdp
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <stdbool.h>
#include <assert.h>

#define MAX_THREAD_NUM		3
#define MAX_TASK_NUM		1000
#define DEBUG				0

#if DEBUG
#define LOG(...)			printf(__VA_ARGS__)
#else
#define LOG(...)
#endif

#define LL_ADD(item, list)	do{	\
	item->ptrPrev = NULL;	\
	item->ptrNext = list;	\
	if(list != NULL)	list->ptrPrev = item;	\
	list = item;	\
}while(0)

#define LL_DEL(item, list)	do{	\
	if(item->ptrPrev != NULL)	item->ptrPrev->ptrNext = item->ptrNext;	\
	if(item->ptrNext != NULL)	item->ptrNext->ptrPrev = item->ptrPrev;	\
	if(item == list)		list = item->ptrNext;	\
	item->ptrNext = NULL;	\
	item->ptrPrev = NULL;	\
}while(0)

//	thread queue
typedef struct tagThreadList{
	pthread_t threadId;
	struct ThreadPool *ptrPool;
	bool isStop;
	struct tagThreadList *ptrPrev;
	struct tagThreadList *ptrNext;
}ThreadList;

//	task queue
typedef struct tagTaskList{
	void (*ptrFunc)(struct tagTaskList *ptrTask, struct ThreadPool *ptrPool);
	int userData;
	struct tagTaskList *ptrPrev;
	struct tagTaskList *ptrNext;
}TaskList;

//	manager parts
typedef struct ThreadPool{
	struct tagThreadList *ptrThreads;
	struct tagTaskList *ptrTasks;
	pthread_cond_t	taskCond;
	pthread_mutex_t	taskMutex;
}ThreadPool;

static void *ThreadCallback(void *arg){
	ThreadList *thread = (ThreadList *)arg;
	LOG("create thread id:%ld\n", thread->threadId);
	while(1){
		pthread_mutex_lock(&thread->ptrPool->taskMutex);
		while(thread->ptrPool->ptrTasks == NULL){
			if(thread->isStop){
				break;
			}
			pthread_cond_wait(&thread->ptrPool->taskCond, &thread->ptrPool->taskMutex);
		}
		if(thread->isStop){
			pthread_mutex_unlock(&thread->ptrPool->taskMutex);
			break;
		}
		TaskList *task = thread->ptrPool->ptrTasks;
		LL_DEL(task, thread->ptrPool->ptrTasks);
		pthread_mutex_unlock(&thread->ptrPool->taskMutex);
		task->ptrFunc(task, thread->ptrPool);
		LOG("id:%ld\t task->userData:%d\n", thread->threadId, task->userData);
	}
	LOG("The index of %ld thread exit\n", thread->threadId);
	if(thread != NULL){
		free(thread);
		thread = NULL;
	}
	pthread_exit(NULL);		// pthread_cancel()
}


int ThreadPoolCreate(ThreadPool *ptrPool, int threadNum){
	if(threadNum < 1)	threadNum = 1;
	if(ptrPool == NULL)	return -1;
	memset(ptrPool, 0, sizeof(ThreadPool));
	pthread_cond_t blankCond = PTHREAD_COND_INITIALIZER;
//	pthread_cond_init(&blank_cond, NULL);
	memcpy(&ptrPool->taskCond, &blankCond, sizeof(pthread_cond_t));
	pthread_mutex_t blankMutex = PTHREAD_MUTEX_INITIALIZER;
//	pthread_mutex_init(&blank_mutex, NULL);
	memcpy(&ptrPool->taskMutex, &blankMutex, sizeof(pthread_mutex_t));

	for(int i = 0; i < threadNum; i++){
		ThreadList *thread = (ThreadList *)malloc(sizeof(ThreadList));
		if(thread == NULL){
			perror("malloc");
			return -2;
		}
		memset(thread, 0, sizeof(ThreadList));
		thread->ptrPool = ptrPool;

		int ret = pthread_create(&thread->threadId, NULL, ThreadCallback, thread);
		if(ret < 0){
			perror("pthread_create");
			free(thread);
			return -3;
		}
		LL_ADD(thread, ptrPool->ptrThreads);
	}
	LOG("ThreadPoolCreate succeed\n");
	return 0;
}

void ThreadPoolDestroy(ThreadPool *ptrPool){
	ThreadList *thread = NULL;
	for(thread = ptrPool->ptrThreads; thread != NULL; thread = thread->ptrNext){
		thread->isStop = true;
	}
	pthread_mutex_lock(&ptrPool->taskMutex);
	pthread_cond_broadcast(&ptrPool->taskCond);
	pthread_mutex_unlock(&ptrPool->taskMutex);
	LOG("ThreadPoolDestroy succeed\n");
}
void ThreadPoolPush(ThreadPool *ptrPool, TaskList *task){
	pthread_mutex_lock(&ptrPool->taskMutex);
	LL_ADD(task, ptrPool->ptrTasks);
	LOG("ThreadPoolPush:%d\n", task->userData);
	pthread_cond_signal(&ptrPool->taskCond);
	pthread_mutex_unlock(&ptrPool->taskMutex);
}

void Func(TaskList *task, ThreadPool *ptrPool){
	static int handleNum = 0;
	handleNum++;
	printf("Processing task, task->userData:%d\n", task->userData);
	if(handleNum == MAX_TASK_NUM){
		LOG("The total processing task number is %d\n", handleNum);
		ThreadPoolDestroy(ptrPool);
	}
}

int main(){
	ThreadPool ptrPool;
	int ret = ThreadPoolCreate(&ptrPool, MAX_THREAD_NUM);
	assert(ret == 0);

	TaskList task[MAX_TASK_NUM];
	for(int i = 0; i < MAX_TASK_NUM; i++){
		task[i].ptrPrev = NULL;
		task[i].ptrNext = NULL;
		task[i].ptrFunc = Func;
		task[i].userData = i;
		ThreadPoolPush(&ptrPool, &task[i]);
	}

	int ind = 1;
	while(1){
		sleep(1);
		printf("count:%d\n", ind++);
	}
	return 0;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C语言实现一个简单的线程池可以按照以下步骤进行: 1. 定义线程池结构体:创建一个结构体,包含线程池中的线程数量、任务队列、互斥锁、条件变量等必要的成员。 ```c typedef struct { pthread_t *threads; // 线程数组 int thread_count; // 线程数量 task_queue_t *task_queue; // 任务队列 pthread_mutex_t mutex; // 互斥锁 pthread_cond_t cond; // 条件变量 int shutdown; // 线程池关闭标志 } thread_pool_t; ``` 2. 定义任务队列结构体:创建一个结构体,用于存储任务队列的信息,包括任务数组、任务数量、头尾指针等成员。 ```c typedef struct { task_t **tasks; // 任务数组 int task_count; // 任务数量 int head; // 队列头指针 int tail; // 队列尾指针 } task_queue_t; ``` 3. 定义任务结构体:创建一个结构体,用于存储具体的任务信息,例如任务函数指针和参数。 ```c typedef struct { void (*function)(void *); // 任务函数指针 void *argument; // 任务参数 } task_t; ``` 4. 初始化线程池:创建线程池,并初始化线程数组、任务队列、互斥锁、条件变量等。 5. 添加任务:将任务添加到任务队列中,并通过条件变量通知线程池中的线程有新任务可执行。 6. 线程函数:线程池中的线程函数,循环从任务队列中取出任务并执行。 7. 等待线程池任务完成:可以通过条件变量等待所有任务执行完毕。 8. 销毁线程池:释放线程池中的资源,包括线程数组、任务队列、互斥锁、条件变量等。 这是一个简单的线程池实现的框架,你可以根据自己的需求进行具体的功能扩展和优化。注意在并发环境中使用互斥锁和条件变量来保证线程安全。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值