c++多线程 线程池的实现

目录

1,简易线程池

XThreadPool.cpp

javascript 复制代码
#include<iostream>
#include<thread>
#include<mutex>
#include<vector>
#include<list>

#include"XTasks.h"


class XThreadPool
{
public:
	void  Init(int num);    //初始化线程数量
	void  Start();          //启动所有线程,必须先调用Init();
	void  AddTask(XTask* task);  //添加任务
	XTask* GetTask();       //获取任务
private:
	void Run();             //线程池中线程的入口函数

private:
	int thread_num = 0;          //线程数量
	std::mutex m_mux;
	std::vector<std::thread*>  m_threads;
	std::list<XTask*>  m_tasks;  //任务列表
	bool isInit = false;         //判断有没有初始化线程池
	std::condition_variable cv;
};


//初始化线程数量
void  XThreadPool::Init(int num)
{
	unique_lock<mutex> lock(m_mux);
	this->thread_num = num;
	isInit = true;
	cout << "threadpool Init" << num << endl;
}

//启动所有线程,必须先调用Init();
void  XThreadPool::Start()
{
	unique_lock<mutex> lock(m_mux);
    if(!isInit)
    { 
		cout << "please  Init thread_num" << endl;
    }
	if (!m_threads.empty())
	{
		cerr << "thread poll has start!" << endl;
	}

	//启动线程
	for (int i = 0;i< thread_num;i++)
	{
		thread* th = new  thread(&XThreadPool::Run, this);
		m_threads.push_back(th);
	}
}

//添加任务
void  XThreadPool::AddTask(XTask* task)
{
	unique_lock<mutex> lock(m_mux);
	m_tasks.push_back(task);
	cv.notify_one();
}

XTask* XThreadPool::GetTask()
{
	unique_lock<mutex> lock(m_mux);
	if (m_tasks.empty())
	{
		cv.wait(lock);
	}
	if (m_tasks.empty())
	{
		return nullptr;
	}
	XTask* tmptask = m_tasks.front();
	m_tasks.pop_front();
	return tmptask;
}


//线程池中线程的入口函数
void XThreadPool::Run()
{
	cout << "begin XThreadPool Run" << this_thread::get_id() << endl;
	while (true)
	{
		XTask* task = GetTask();
		if (task == nullptr) {
			continue;
		}
		try {
			task->Run();
		}
		catch (...)
		{

		}
	}
	//cout << "end XThreadPool Run" << this_thread::get_id() << endl;
}

XTask.cpp

javascript 复制代码
#include<iostream>
#include<thread>


class  XTask
{
public:
	virtual int Run() = 0;
};

class MyTask :public XTask
{
	int Run() override;
};

int MyTask::Run()
{
    cout << "this threadID is " << this_thread::get_id() << endl;
    cout << "MyTask " << endl;
    return 0;
}

main.cpp

javascript 复制代码
#include<thread>
#include<iostream>

#include"XThreadPool.h"
#include"XTasks.h"
using namespace std;

int main()
{
	XThreadPool  thpool;
	thpool.Init(16);
	thpool.Start();

	MyTask task1;
	thpool.AddTask(&task1);

	getchar();
}
相关推荐
郝学胜_神的一滴2 天前
CMake 034:生成器表达式:解耦构建时序、精简分支逻辑的终极利器
c++·cmake
见过夏天2 天前
C++ 基础入门完全指南
c++
用户805533698034 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
BadBadBad__AK4 天前
线段树维护区间 k 次方和
c++·数学·算法·stl
卷无止境5 天前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
卷无止境5 天前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
郝学胜_神的一滴6 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
卷无止境8 天前
C++ 的Eigen 库全解析
c++
卷无止境8 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴8 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake