线程池
利用一个队列作为线程池的存放容器
queue.h
#ifndef QUEUE_H
#define QUEUE_H
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct Queue
{
void** arr;
int cal;
int front;
int rear;
}Queue;
//创建队列
Queue* create_queue(int cal);
//销毁队列
void destroy_queue(Queue* queue);
//入队
void push_queue(Queue* queue,void* arg);
//出队
void pop_queue(Queue* queue,void* arg);
//队空
bool empty_queue(Queue* queue);
//队满
bool full_queue(Queue* queue);
//队头
void* front_queue(Queue* queue);
//队尾
void*rear_queue(Queue* queue);
#endif// QUEUE_H
pool.h
#ifndef POOL_H
#define POOL_H
#include <pthread.h>
#include <stdlib.h>
#include "queue.h"
typedef void(*EnterFP)(void*);
typedef struct ThreadPool
{
int thread_cnt;
pthread_t* tids;
Queue* store;
EnterFP enter;
pthread_mutex_t hlock;
pthread_mutex_t tlock;
pthread_cond_t empty;
pthread_cond_t full;
}ThreadPool;
//创建线程池
ThreadPool* create_threadpool(int thread_cnt,int store_cal,EnterFP enter);
//启动线程池
void start_threadpool(ThreadPool* thread);
//线程池出队
void* pop_threadpool(ThreadPool* thread);
//线程池入队
void push_threadpool(ThreadPool* thread,void*task);
//摧毁线程池
void destroy_threadpool(ThreadPool* thread);
#endif// POOL_H
pool.c
#include "pool.h"
//线程入口函数
static void* run(void* arg)
{
ThreadPool* thread = arg;
for(;;)
{
void* task = pop_threadpool(thread);
thread->enter(task);
}
}
ThreadPool* create_threadpool(int thread_cnt,int store_cal,EnterFP enter)
{
ThreadPool* thread = malloc(sizeof(ThreadPool));
thread->tids = malloc(sizeof(pthread_t)*thread_cnt);
thread->store = create_queue(store_cal);
thread->thread_cnt = thread_cnt;
thread->enter = enter;
pthread_mutex_init(&thread->hlock,NULL);
pthread_mutex_init(&thread->tlock,NULL);
pthread_cond_init(&thread->empty,NULL);
pthread_cond_init(&thread->full,NULL);
return thread;
}
void start_threadpool(ThreadPool* thread)
{
for(int i=0;i<thread->thread_cnt;i++)
{
pthread_create(thread->tids+1,NULL,run,thread);
}
}
void* pop_threadpool(ThreadPool* thread)
{
pthread_mutex_lock(&thread->hlock);
while(empty_queue(thread->store))
{
pthread_cond_signal(&thread->full);
pthread_cond_wait(&thread->empty,&thread->hlock);
}
void* task =front_queue(thread->store);
pthread_cond_signal(&thread->full);
pthread_mutex_unlock(&thread->hlock);
return task;
}
void push_threadpool(ThreadPool* thread,void*task)
{
pthread_mutex_lock(&thread->tlock);
while(full_queue(thread->store))
{
pthread_cond_signal(&thread->empty);
pthread_cond_wait(&thread->full,&thread->tlock);
}
push_queue(thread->store,task);
pthread_cond_signal(&thread->empty);
pthread_mutex_unlock(&thread->tlock);
}
void destroy_threadpool(ThreadPool* thread)
{
pthread_cond_destroy(&thread->full);
pthread_cond_destroy(&thread->empty);
pthread_mutex_destroy(&thread->tlock);
pthread_mutex_destroy(&thread->hlock);
destroy_queue(thread->store);
free(thread->tids);
free(thread);
}