#include<stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
typedef struct task{
void (*run)(void *);
void* arg;
struct task* next;
}task;
typedef struct threadpool{
task* first; //指向任务队列的起始位置
task* end; //指向任务队列的末尾位置
int threadNUM;//线程数量
int tasksize;//任务数量
pthread_mutex_t mutexpool;//锁整个线程池
pthread_cond_t notempty;//任务队列是不是空
int shutdown;//是不是要销毁线程池,销毁为1,不销毁为0
}threadpool;
void* worker(void* arg){
//puts("1111112222");
threadpool* p = (threadpool*) arg;
while(1){
pthread_mutex_lock(&p->mutexpool);
while(p->tasksize == 0 || p->first == NULL){
pthread_cond_wait(&p->notempty,&p->mutexpool);
if(p->shutdown){
pthread_mutex_unlock(&p->mutexpool);
pthread_exit(NULL);
}
}
if(p->shutdown){
pthread_mutex_unlock(&p->mutexpool);
pthread_exit(NULL);
}
//puts("2222");
task *t = p->first;
p->first = t->next;
p->tasksize--;
pthread_mutex_unlock(&p->mutexpool);
t->run(t->arg);
free(t);
}
return NULL;
}
threadpool* threadpoolinit(int threadNUM){
int tii = 0;
threadpool* now = malloc(sizeof(*now));
now->first = NULL;
now->end = NULL;
now->threadNUM = threadNUM;
now->tasksize = 0;
now->shutdown = 0;
pthread_cond_init(&now->notempty,NULL);
pthread_mutex_init(&now->mutexpool,NULL);
for(int i = 1; i <= threadNUM ; i++){
pid_t pid;tii++;
//puts("21132123");
pthread_create(&pid,NULL,worker,now);
}
printf("ti = %d",tii);
return now;
}
void threadpooldestroy(threadpool* now){
pthread_mutex_lock(&now->mutexpool);
now->shutdown = 1;
for(int i=0;i<pool->threadNUM;i++)
{
pthread_cond_signal(&pool->notempty);
}
pthread_mutex_unlock(&now->mutexpool);
for(int i = 1; i<= now->threadNUM;i++) wait(NULL);
pthread_mutex_destroy(&now->mutexpool);
pthread_cond_destroy(&now->notempty);
free(now);
}
void addTask(void (*f)(void *),void* arg,threadpool* p){
task *t= malloc(sizeof(*t));
t->run = f;
t->arg = arg;
t->next = NULL;
pthread_mutex_lock(&p->mutexpool);
if(p->first == NULL)
{
//puts("no");
p->first = t;
p->end = t;
}
else{
//puts("yes");
p->end->next = t;
p->end = t;
}
p->tasksize++;
pthread_mutex_unlock(&p->mutexpool);
pthread_cond_signal(&p->notempty);
return;
}
void printit(void* numm){
//puts("3333");
int num = numm;
printf("%d\n",num);
}
int main(){
threadpool* t = threadpoolinit(2);
puts("1111");
addTask(printit,1,t);
addTask(printit,2,t);
addTask(printit,3,t);
addTask(printit,4,t);
/*threadpoolAdd(t,printit,1);
threadpoolAdd(t,printit,2);
threadpoolAdd(t,printit,3);
threadpoolAdd(t,printit,4);*/
sleep(1);//为了测试
threadpooldestroy(t);
return 0;
}