欢迎来到天天文库
浏览记录
ID:37863298
大小:14.39 KB
页数:6页
时间:2019-06-01
《LINUXC线程池》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、#include#include#include#include#include#include/**线程池里所有运行和等待的任务都是一个CThread_worker*由于所有任务都在链表里,所以是一个链表结构*/typedefstructworker{/*回调函数,任务运行时会调用此函数,注意也可声明成其它形式*/void*(*process)(void*arg);void*arg;/*回调函数的
2、参数*/structworker*next;}CThread_worker;/*线程池结构*/typedefstruct{pthread_mutex_tqueue_lock;pthread_cond_tqueue_ready;/*链表结构,线程池中所有等待任务*/CThread_worker*queue_head;/*是否销毁线程池*/intshutdown;pthread_t*threadid;/*线程池中允许的活动线程数目*/intmax_thread_num;/*当前等待队列的任务数目*/intcur_queue_s
3、ize;}CThread_pool;intpool_add_worker(void*(*process)(void*arg),void*arg);void*thread_routine(void*arg);staticCThread_pool*pool=NULL;voidpool_init(intmax_thread_num)//初始化线程池{pool=(CThread_pool*)malloc(sizeof(CThread_pool));pthread_mutex_init(&(pool->queue_lock),NUL
4、L);pthread_cond_init(&(pool->queue_ready),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(max_thread_num*sizeof(pthread_t));inti=0;for(i=0;i5、eate(&(pool->threadid[i]),NULL,thread_routine,NULL);}}/*向线程池中加入任务*/intpool_add_worker(void*(*process)(void*arg),void*arg){/*构造一个新任务*/CThread_worker*newworker=(CThread_worker*)malloc(sizeof(CThread_worker));newworker->process=process;newworker->arg=arg;newworker->n6、ext=NULL;/*别忘置空*/pthread_mutex_lock(&(pool->queue_lock));/*将任务加入到等待队列中*/CThread_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);poo7、l->cur_queue_size++;pthread_mutex_unlock(&(pool->queue_lock));/*好了,等待队列中有任务了,唤醒一个等待线程;注意如果所有线程都在忙碌,这句没有任何作用*/pthread_cond_signal(&(pool->queue_ready));return0;}/*销毁线程池,等待队列中的任务不会再被执行,但是正在运行的线程会一直把任务运行完后再退出*/intpool_destroy(){if(pool->shutdown)return-1;/*防止两次调用*/po8、ol->shutdown=1;/*唤醒所有等待线程,线程池要销毁了*/pthread_cond_broadcast(&(pool->queue_ready));/*阻塞等待线程退出,否则就成僵尸了*/inti;for(i=0;imax_thread_num;i++)pthread_join
5、eate(&(pool->threadid[i]),NULL,thread_routine,NULL);}}/*向线程池中加入任务*/intpool_add_worker(void*(*process)(void*arg),void*arg){/*构造一个新任务*/CThread_worker*newworker=(CThread_worker*)malloc(sizeof(CThread_worker));newworker->process=process;newworker->arg=arg;newworker->n
6、ext=NULL;/*别忘置空*/pthread_mutex_lock(&(pool->queue_lock));/*将任务加入到等待队列中*/CThread_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);poo
7、l->cur_queue_size++;pthread_mutex_unlock(&(pool->queue_lock));/*好了,等待队列中有任务了,唤醒一个等待线程;注意如果所有线程都在忙碌,这句没有任何作用*/pthread_cond_signal(&(pool->queue_ready));return0;}/*销毁线程池,等待队列中的任务不会再被执行,但是正在运行的线程会一直把任务运行完后再退出*/intpool_destroy(){if(pool->shutdown)return-1;/*防止两次调用*/po
8、ol->shutdown=1;/*唤醒所有等待线程,线程池要销毁了*/pthread_cond_broadcast(&(pool->queue_ready));/*阻塞等待线程退出,否则就成僵尸了*/inti;for(i=0;imax_thread_num;i++)pthread_join
此文档下载收益归作者所有