#include<stdio.h>#include<stdlib.h>#include<pthread.h>#include<unistd.h>#include<sys/time.h>#include"./thread_pool.h"staticintmytraver(void*data);staticvoid*runner(void*arg){thread_pool_t*me = arg;while(1){pthread_mutex_lock(&me->tast_mutex);while(llist_head_look(me->task)==NULL){pthread_cond_wait(&me->task_cond,&me->tast_mutex);if(me->stop ==1){break;}}task_t*task_cur =llist_pop_first(me->task);pthread_mutex_unlock(&me->tast_mutex);if(task_cur ==NULL){break;}
task_cur->task_cb(task_cur->arg);free(task_cur->arg);free(task_cur);}printf("thread %lu exit.\n",pthread_self());pthread_exit(0);}staticintpool_thread_create(thread_pool_t*pool){thread_pool_t*me = pool;pthread_t pid;int i =0;for(i =0; i < me->thread_num; i++){if(pthread_create(&pid,NULL, runner, me)!=0){return-1;}printf("create thread[%d] success.\n", i +1);}return0;}intthread_pool_init(thread_pool_t**pool,int thread_num){thread_pool_t*me =(thread_pool_t*)malloc(sizeof(*me));if(me ==NULL){return-1;}
me->thread_num = thread_num;int ret =0;
ret =llist_init(&me->task);if(ret){return-2;}
me->stop =0;if(pthread_mutex_init(&me->tast_mutex,NULL)!=0){return-3;}if(pthread_cond_init(&me->task_cond,NULL)!=0){return-3;}pool_thread_create(me);*pool = me;return0;}staticintmycompare(void*a,void*b){return1;}staticintmytraver(void*data){task_t*task = data;printf("[%d]",*(int*)task->arg);return0;}inttask_post(thread_pool_t*pool, task_callback task_cb,void*arg){thread_pool_t*me = pool;if(me->stop ==1){printf("thread_pool stop will,can't post task!\n");return1;}task_t*cur =(task_t*)malloc(sizeof(*cur));if(cur ==NULL){return-1;}
cur->task_cb = task_cb;
cur->arg = arg;pthread_mutex_lock(&me->tast_mutex);int ret =llist_insert(me->task, cur, mycompare);pthread_mutex_unlock(&me->tast_mutex);if(ret ==0){// llist_traver(me->task, mytraver);pthread_cond_signal(&me->task_cond);}else{return-2;}return0;}intthread_pool_destroy(thread_pool_t*pool){thread_pool_t*me = pool;
me->stop =1;pthread_mutex_lock(&me->tast_mutex);while(1){if(llist_head_look(me->task)==NULL){break;}else{pthread_cond_broadcast(&me->task_cond);structtimeval now;structtimespec outtime;gettimeofday(&now,NULL);
outtime.tv_sec = now.tv_sec +5;// s
outtime.tv_nsec = now.tv_usec *1000;//微妙转为纳秒pthread_cond_timedwait(&me->task_cond,&me->tast_mutex,&outtime);}}pthread_mutex_unlock(&me->tast_mutex);pthread_cond_broadcast(&me->task_cond);return0;}
test.c
#include<stdio.h>#include<stdlib.h>#include<unistd.h>#include"./thread_pool.h"intmyprint(void*arg){int*p = arg;printf("num = %d\n",*p);sleep(1);return0;}intmain(){thread_pool_t*pool;int ret =0;
ret =thread_pool_init(&pool,10);if(ret){puts("init()");exit(1);}int i =0;int res =0;for(i =0; i <1024; i++){int*p =(int*)malloc(sizeof(*p));*p = i +1;
res =task_post(pool, myprint, p);#if0if(res){printf("task[%d] post error.\n", i +1);}else{printf("task[%d] post success.\n", i +1);}#endif// sleep(1);}// pause();thread_pool_destroy(pool);pause();exit(0);}