实现线程池LinuxC版本

线程池的作用
在多线程的应用中,线程的频繁创建和销毁会浪费时间,从而影响效率,所以引进线程池和概念,将多个线程维护在线程池中,避免了线程频繁创建与销毁的开销问题
线程池的结构
结构体
struct threadpool_t{
    pthread_mutex_t lock;         //互斥锁
    pthread_cond_t notify;        //条件变量:配合互斥锁来避免死锁
    pthread_t *threads;           //线程数组
    threadpool_task_t *queue;     //任务队列
    int thread_count;             //线程数
    int queue_size;               //任务数
    int head;                     //头部元素
    int rail;                     //尾部元素
    int count;                    //等待的任务数
    int shutdown;                 //关闭状态
    int started;                  //已经启动的线程数
}
函数
//线程池创建threadpool_t *threadpool_create(int thread_count,int queue_size,int flags);
//添加任务
int threadpool_add(threadpool_t *pool, void (*function)(void *),void *argument, int flags);
//线程池销毁
int threadpool_destroy(threadpool_t *pool, int flags);
//线程池释放
int threadpool_free(threadpool_t *pool);
//为线程池分配任务
static void *threadpool_thread(void *threadpool);
线程池创建
- 给线程池申请空间
 - 初始化成员变量,为线程数组和任务队列申请空间,初始化锁
 - 给线程数组创建进程(?)
 
threadpool_t *threadpool_create(int thread_count,int queue_size,int flags){
    threadpool_t *pool;
    do{
        if(thread_count <= 0 || thread_count > MAX_THREADS || queue_size <= 0|| queue_size > MAX_QUEUE) return NULL;
        if((pool = (threadpool_t *)malloc(sizeof(threadpool_t))) == NULL) break;
        pool->thread_count = 0;
        pool->queue_size = queue_size;
        pool->head = pool->tail = pool->count = pool->shutdown = pool->started = 0;
    }
}
以上是 实现线程池LinuxC版本 的全部内容, 来源链接: utcz.com/z/519781.html

