C++实现简单线程池

线程池,就是有一堆已经创建好的线程,初始时他们处于空闲状态,并用锁(互斥量)将他们锁住,但有一个任务进来时,解锁并分配一个线程处理任务,当任务处理完后,线程又重新回到线程池在锁住;当线程池中的线程都在执行任务的时候,这个时候再有任务进来,只能等线程池中的线程处理完后再才能执行。

为什么要用线程池
我们用多线程来处理任务,单线程也不能一味的无止境的使用,一直都开新的线程会给系统带来大量的消耗,并且线程是可以重复使用的,所以我们创建线程池来用有限的线程处理无限的任务。

-------------------.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();
}
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

watchman_Xu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值