文档介绍:C语言实现简单线程池有时我们会需要大量线程来处理一些相互独立的任务,为了避免频繁的申请释放线程所带来的开销,我们可以使用线程池。下面是一个C语言实现的简单的线程池。头文件:1:#ifndefTHREAD_POOL_H__2:#HREAD_POOL_H__3:4:#include<>5:6:/*要执行的任务链表*/7:typedefstructtpool_work{8:void*(*routine)(void*);/*任务函数*/9:void*arg;/*传入任务函数的参数*/10:structtpool_work*next;11:}tpool_work_t;12:13:typedefstructtpool{14:intshutdown;/*线程池是否销毁*/15:intmax_thr_num;/*最大线程数*/16:pthread_t*thr_id;/*线程ID数组*/17:tpool_work_t*queue_head;/*线程链表*/18:pthread_mutex_tqueue_lock;19:pthread_cond_tqueue_ready;20:}tpool_t;21:22:/*23:****@brief创建线程池24:****@parammax_thr_num最大线程数25:****@return0:成功其他:失败26:*/27:int28:tpool_create(intmax_thr_num);29:30:/*31:****@brief销毁线程池32:*/33:void34:tpool_destroy();35:36:/*37:****@brief向线程池中添加任务38:****@paramroutine任务函数指针39:****@paramarg任务函数参数40:****@return0:成功其他:失败41:*/42:int43:tpool_add_work(void*(*routine)(void*),void*arg);44:45:#endif实现:1:#include<>2:#include<>3:#include<>4:#include<>5:#include<>6:7:#include""8:9:statictpool_t*tpool=NULL;10:11:/*工作者线程函数,从任务链表中取出任务并执行*/12:staticvoid*13:thread_routine(void*arg)14:{15:tpool_work_t*work;16:17:while(1){18:/*如果线程池没有被销毁且没有任务要执行,则等待*/19:pthread_mutex_lock(&tpool->queue_lock);20:while(!tpool->queue_head&&!tpool->shutdown){21:pthread_cond_wait(&tpool->queue_ready,&tpool->queue_lock);22:}23:if(tpool->shutdown){24:pthread_mutex_unlock(&tpool->queue_lock);25:pthread_exit(NULL);26:}27:work=tpool->queue_head;28:tpool->queue_head=tpool->queue_head->next;29:pthread_mutex_unlock(&tpool->queue_lock);30:31:work->routine(work->arg);32:free(work);33:}34:35:returnNULL;36:}37:38:/*39:*创建线程池40:*/41:int42:tpool_create(intmax_thr_num)43:{44:inti;45:46:tpool=calloc(1,sizeof(tpool_t));47:if(!tpool){48:printf("%s:callocfailed\n",__FUNCTION__);49:exit(1);50:}51:52:/*初始化*/53:tpool->max_thr_num=max_thr_num;54:tpool->shutdown=0;55:tpool->queue_head=NULL;56:if(pthread_mutex_init(&tpool->queue_lock,NULL)!=0){57:printf("%s:pthread_mutex_initfailed,errno:%d,error:%s\n",58:__FUNCTION__,errno,strerror(errno));59:exit(1);60: