线程池
线程池:因为线程在频繁的进行创建和销毁过程中浪费CPU资源,线程池就是把一堆线程放在一个池子里面进行统一管理;
线程池工作流程:
1、初始化线程池,任务队列和工作线程;
2、向任务队列中添加任务;
3、将等候在条件变量(任务队列上有任务)上的一个线程唤醒并从该任务队列中取出第一个任务给该线程执行;
4、等待任务队列中所有任务执行完毕
5、关闭线程池;
线程池的构成
任务队列job_queue:用于存放待处理的函数,包含的成员有void *(*)(void *):用于表示处理函数,void *arg:用于表示参数选项,struct job_queue* pnext:队列指针;
worker:表示工作线程,用于处理任务;
thread_pool:表示线程池,作用是管理多个线程并且提供任务队列的接口;使用的函数包括:thread_pool_init():用于初始化线程池thread_pool_destory():用于销毁线程,thread_pool_dd_job():用于添加线程池任务;
一个线程池的例子
thread_pool_test.c
#include
#include
#include "thread_pool.h"
void* test(void* arg){
printf("%lu do job %d\n",pthread_self(),(int)arg);
}
int main(int argc,char* argv[]){
if(3 != argc){
printf("usage:%s \n",argv[0]);
return 1;
}
int nthread = atoi(argv[1]);
if(nthread <= 0){
printf("nthread must >0");
return 1;
}
struct threadpool* ppool = threadpool_init(nthread);
int njobs = atoi(argv[2]);
int i;
for(i=1;i
threadpool_add_job(ppool,test,(void*)i);
}
//pause();
threadpool_destroy(ppool);
}
线程池编程需要包含的头文件
thread_pool.h
#pragma once
#ifndef _THREAD_POOL_H_
#define _THREAD_POOL_H_
#include
#include
#include
#include
struct threadpool;
struct threadpool* threadpool_init(int nthreads);
void threadpool_add_job(struct threadpool* ppool,void* (*func)(void*),void* arg);
void threadpool_destroy(struct threadpool* ppool);
#endif