线程池,就是有一堆已经创建好的线程,初始时他们处于空闲状态,并用锁(互斥量)将他们锁住,但有一个任务进来时,解锁并分配一个线程处理任务,当任务处理完后,线程又重新回到线程池在锁住;当线程池中的线程都在执行任务的时候,这个时候再有任务进来,只能等线程池中的线程处理完后再才能执行。
为什么要用线程池?
我们用多线程来处理任务,单线程也不能一味的无止境的使用,一直都开新的线程会给系统带来大量的消耗,并且线程是可以重复使用的,所以我们创建线程池来用有限的线程处理无限的任务。
-------------------.h文件
#ifndef THREADPOOL_H
#define THREADPOOL_H
#include <iostream>
#include <queue>
#include <pthread.h>
#include <unistd.h>
using namespace std;
//定义任务类型
typedef void (*Task)(void);
class Threadpool
{
//定义任务队列
queue<Task> taskQueue;
//最大任务数量
size_t maxCount;
//当前任务数量
size_t cuiCount;
//条件变量
pthread_cond_t null;
//互斥量
pthread_mutex_t lock;
public:
//构造函数,确定线程池的线程数
Threadpool(size_t cntThread,size_t maxCount);
//析构函数
~Threadpool(void);
//添加任务
bool addTask(Task task);
//线程入口
static void* start(void*);
};
#endif//THREADPOOL_H
--------------------------------.cpp文件
#include "threadpool.h"
//构造函数,确定线程池的线程数
Threadpool::Threadpool(size_t cntThread,size_t maxCount)
{
//初始化条件变量与互斥量
pthread_mutex_init(&lock,NULL);
pthread_cond_init(&null,NULL);
//创建线程
pthread_t pid[cntThread];
for(int i=0; i<maxCount; i++)
{
pthread_create(pid+i,NULL,start,this);
}
}
//析构函数
Threadpool::~Threadpool(void)
{
//销毁条件变量与互斥量
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&null);
}
//添加任务
bool Threadpool::addTask(Task task)
{
//加锁
pthread_mutex_lock(&lock);
//检查任务数量
if(taskQueue.size() >= maxCount)
{
cout << "任务已经满了" << endl;
pthread_mutex_unlock(&lock);
return false;
}
//加入任务到队列
taskQueue.push(task);
//唤醒空状态进入睡眠的线程
pthread_cond_broadcast(&null);
//解锁
pthread_mutex_unlock(&lock);
}
//线程入口
void* Threadpool::start(void* arg)
{
Threadpool* thread = (Threadpool*)arg;
while(true)
{
//加锁访问任务队列
pthread_mutex_lock(&thread->lock);
while(thread->taskQueue.empty())
{
cout << pthread_self() << ":没活了,洗洗睡吧!" << endl;
pthread_cond_wait(&thread->null,&thread->lock);
}
//从队列中获取任务
Task task = thread->taskQueue.front();
thread->taskQueue.pop();
//先解锁,因为不知道任务需要执行多久
pthread_mutex_unlock(&thread->lock);
//执行任务
task();
}
}
--------------------------------------------main.cpp
#include "threadpool.h"
#include <stdlib.h>
void work(void)
{
int cnt = rand() % 10;
for(int i=0; i<rand(); i++)
{
cout << pthread_self() << ":" << i << endl;
sleep(1);
}
}
int main()
{
pthread_t pid[3] = {};
int cnt = 0;
Threadpool* thread = new Threadpool(3,8);
while(true)
{
cout << "请输入要添加的任务数:" << endl;
cin >> cnt;
for(int i=0; i<10; i++)
{
thread->addTask(work);
}
}
pause();
}