thread_pool.h
/*************************************************************************
> File Name: thrread_pool.h
> Author: arrayli
> Mail: 1374367549@qq.com
> Created Time: 2018年03月04日 星期日 15时11分38秒
************************************************************************/
#ifndef _THRREAD_POOL_H
#define _THRREAD_POOL_H
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#define DEFAULT_TIME 10 /* 10s 检测一次 */
#define MIN_WAIT_TASK_NUM 10 /* 如果 queue_size > MIN_WAIT_TASK_NUM 添加新的线程到线程池 */
#define DEFAULT_THREAD_VARY 10 /* 每次创建和销毁的线程个数 */
#define true 1
#define false 0
typedef struct
{
void*(*function)(void*); /* 函数指针,执行回调函数 */
void *arg; /* 上面函数的 参数 */
}threadpool_task_t; /* 各子线程任务结构体 */
/* 描述线程池相关信息 */
typedef struct threadpool_t
{
pthread_mutex_t lock; /* 用于锁住本结构体 */
pthread_mutex_t thread_counter; /* 记录忙状态线程个数的锁 ---- busy_thr_num */
pthread_cond_t queue_not_full; /* 当任务队列满时,添加任务的线程阻塞,等待此条件变量 */
pthread_cond_t queue_not_empty; /* 任务队列里不为空,通知等待任务的线程 */
pthread_t *threads; /* 存放线程池中每个线程的 tid ,数组 */
pthread_t adjust_tid; /* 存放管理线程 tid */
threadpool_task_t *task_queue; /* 任务队列 */
int max_thr_num; /* 线程池最大线程数 */
int min_thr_num; /* 线程池最小线程数 */
int busy_thr_num; /* 忙状态线程个数 */
int live_thr_num; /* 当前存活线程个数 */
int wait_exit_thr_num; /* 要销毁的线程个数 */
int queue_front; /* task_queue 队头下标 */
int queue_rear; /* task_queue 队尾下标 */
int queue_size; /* task_queue 队中实际任务数 */
int queue_max_size; /* task_queue 队列可容纳任务数上限 */
int shutdown; /* 标志位 线程池使用状态 true 或 false */
}threadpool_t ;
/* typedef struct threadpool_t threadpool_t; */
void *threadpool_create(int min_thr_num,int max_thr_num,int queue_max_size);
void *threadpool_thread(void *arg);
void *adjust_thread(void*arg);
int threadpool_add(threadpool_t* pool,void*(*function)(void *arg),void *arg);
int threadpool_free(threadpool_t *pool);
int is_thread_alive(pthread_t tid);
int threadpool_destroy(threadpool_t *pool);
#endif
thread_pool.c
/*************************************************************************
> File Name: thrread_pool.c
> Author: arrayli
> Mail: 1374367549@qq.com
> Created Time: 2018年03月04日 星期日 15时12分33秒
************************************************************************/
#include<stdio.h>
#include<unistd.h>
#inc