线程池
1. 概念
通俗的讲就是一个线程的池子,可以循环的完成任务的一组线程集合
必要性:
我们平时创建一个线程,完成某一个任务,等待线程的退出。但当需要创建大量的线程时,假设T1为创建线程时间,T2为在线程任务执行时间,T3为线程销毁时间,当 T1+T3 > T2,这时候就不划算了,使用线程池可以降低频繁创建和销毁线程所带来的开销,任务处理时间比较短的时候这个好处非常显著。
线程池的基本结构:
1 任务队列,存储需要处理的任务,由工作线程来处理这些任务
2 线程池工作线程,它是任务队列任务的消费者,等待新任务的信号
2. 实现步骤
2.1创建线程池的基本结构
任务队列结构体
typedef struct Task
{
void *(*func)(void *arg); //要执行的任务
void *arg; //参数
struct Task *next; //指针域
}Task;
线程池结构体
typedef struct ThreadPool
{
pthread_mutex_t taskLock; //互斥锁
pthread_cond_t newTask; //条件变量
pthread_t tid[POOL_NUM]; //线程号
Task *queue_head; //任务头
int busywork; //判断线程是否都在忙
}ThreadPool;
2.2 线程池的初始化
pool_init
{
创建一个线程池结构
实现任务队列互斥锁和条件变量的初始化
创建n个工作线程
}
2.3 线程池添加任务
pool_add_task
{
判断是否有空闲的工作线程
给任务队列添加一个节点
给工作线程发送信号newtask
}
2.4 实现工作线程
workThread
{
while(1)
{
等待newtask任务信号
从任务队列中删除节点
执行任务
}
}
2.5 线程池的销毁
pool_destory
{
删除任务队列链表所有节点,释放空间
删除所有的互斥锁条件变量
删除线程池,释放空间
}
3.代码实现
实现一个固定大小的线程池
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define POOL_NUM 10
/* 任务队列结点 */
typedef struct Task
{
void *(*func)(void *arg);
void *arg;
struct Task *next;
}Task;
/* 线程池结构体 */
typedef struct ThreadPool
{
pthread_mutex_t taskLock;
pthread_cond_t newTask;
pthread_t tid[POOL_NUM];
Task *queue_head;
int busywork;
}ThreadPool;
ThreadPool *pool;
void *workThread(void *arg)
{
while(1)
{
pthread_mutex_lock(&pool->taskLock);
pthread_cond_wait(&pool->newTask,&pool->taskLock);
Task *ptask = pool->queue_head;
pool->queue_head = pool->queue_head->next;
pool->busywork--;
pthread_mutex_unlock(&pool->taskLock);
ptask->func(ptask->arg);
}
}
void *realwork(void *arg)
{
printf("Finish work %d\n",(int)arg);
}
void pool_add_task(int arg)
{
Task *newTask;
pthread_mutex_lock(&pool->taskLock);
while(pool->busywork>=POOL_NUM)
{
pthread_mutex_unlock(&pool->taskLock);
usleep(10000);
pthread_mutex_lock(&pool->taskLock);
}
pthread_mutex_unlock(&pool->taskLock);
newTask = malloc(sizeof(Task));
newTask->func = realwork;
newTask->arg = arg;
pthread_mutex_lock(&pool->taskLock);
Task *member = pool->queue_head;
if(member==NULL)
{
pool->queue_head = newTask;
}
else
{
while(member->next!=NULL)
{
member=member->next;
}
member->next = newTask;
}
pool->busywork++;
pthread_cond_signal(&pool->newTask);
pthread_mutex_unlock(&pool->taskLock);
}
void pool_init()
{
pool = malloc(sizeof(ThreadPool));
pthread_mutex_init(&pool->taskLock,NULL);
pthread_cond_init(&pool->newTask,NULL);
pool->queue_head = NULL;
pool->busywork=0;
for(int i=0;i<POOL_NUM;i++)
{
pthread_create(&pool->tid[i],NULL,workThread,NULL);
}
}
void pool_destory()
{
Task *head;
while(pool->queue_head!=NULL)
{
head = pool->queue_head;
pool->queue_head = pool->queue_head->next;
free(head);
}
pthread_mutex_destroy(&pool->taskLock);
pthread_cond_destroy(&pool->newTask);
free(pool);
}
int main()
{
pool_init();
sleep(20);
for(int i=1;i<=20;i++)
{
pool_add_task(i);
}
sleep(5);
pool_destory();
}