69,394
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include<sys/mman.h>
#include<pthread.h>
#include<semaphore.h>
#include <netinet/in.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<sys/select.h>
#include<sys/epoll.h>
#include<unistd.h>
#include<dirent.h>
#include<pwd.h>
#include<grp.h>
#include<time.h>
#include<errno.h>
#include<signal.h>
#include<fcntl.h>
#include<sys/wait.h>
#include<stdbool.h>
typedef void Fun(void*);
typedef struct work_t{
Fun* fun;
void*arg;
struct work_t*next;
}work_t;
typedef struct trdpool_t{
pthread_t *phead;
work_t *whead;
pthread_cond_t cond;
pthread_mutex_t mutex;
bool status; //0 线程池不销毁 1 销毁
int num;
}trdpool_t;
trdpool_t *trdpool=NULL;
void print_pthread_self(void*arg)
{
//sleep(3);
printf("pthread id = %ld\n",pthread_self());
//sleep(2);
return ;
}
void*start_routine(void*arg)
{
// puts("!");
work_t*work;
while(1){
pthread_mutex_lock(&trdpool->mutex);
// puts("?");
while( trdpool->whead==NULL&& trdpool->status==0){ //一个小朋友把蛋糕抢走了,那么其他小朋友醒来再继续睡。
fprintf(stdout,"thread %ld is ready \n",pthread_self());
pthread_cond_wait(& trdpool->cond,& trdpool->mutex);
sleep(1);
fprintf(stdout,"thread %ld is weak up \n",pthread_self());
}
if( trdpool->status==0){
work= trdpool->whead;
trdpool->whead= trdpool->whead->next;
pthread_mutex_unlock(& trdpool->mutex);
(work->fun)(work->arg);
free(work);
}else{
pthread_mutex_unlock(& trdpool->mutex);
pthread_exit(NULL);
}
}
}
void add_work()
{
work_t* new_work=malloc(sizeof(work_t));
work_t* old_work;
new_work->arg=NULL;
new_work->fun=print_pthread_self;
new_work->next=NULL;
pthread_mutex_lock(& trdpool->mutex);
if( trdpool->whead!=NULL){
old_work= trdpool->whead;
trdpool->whead=new_work;
new_work->next=old_work;
}else{
trdpool->whead=new_work;
}
pthread_cond_signal(& trdpool->cond);
pthread_mutex_unlock(& trdpool->mutex);
}
void prdpool_init(int num)
{
trdpool=malloc(sizeof(trdpool_t));
pthread_mutex_init(& trdpool->mutex,NULL);
pthread_cond_init(& trdpool->cond,NULL);
trdpool->status=0;
trdpool->phead=malloc(sizeof(pthread_t)*num);
trdpool->num=num;
for(int i=0;i<num;i++)
pthread_create( trdpool->phead+i,NULL,start_routine,NULL);
}
void prdpool_destory()
{
puts("the trdpool begin to destory !");
work_t *work;
trdpool->status=1;
int ret=pthread_mutex_lock(& trdpool->mutex);
pthread_cond_broadcast(& trdpool->cond);
pthread_mutex_unlock(& trdpool->mutex);
for(int i=0;i< trdpool->num;i++){
pthread_join( trdpool->phead[i],NULL);
}
free( trdpool->phead);
work=trdpool->whead;
while(trdpool->whead){
// puts("!");
trdpool->whead=trdpool->whead->next;
free(work);
work=trdpool->whead;
}
pthread_cond_destroy(& trdpool->cond);
pthread_mutex_destroy(& trdpool->mutex);
free(trdpool);
puts("the trdpool destory !");
}
int main(int argc,char**argv)
{
prdpool_init(5);
for(int i=0;i<200;i++)
add_work();
sleep(5);
// while(1);
prdpool_destory();
return 0;
}