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();
}
相关推荐
HappyBoy_20192 小时前
MybatisPlus IPage分页查询工具类
java·开发语言
爱敲点代码的小哥2 小时前
类型转换 递归算法 编译错误 装箱和拆箱 知识点
开发语言·c#
福楠2 小时前
从C到C++ | 内存管理
c语言·c++
南风微微吹2 小时前
【2026年3月最新】计算机二级Python题库下载安装教程~共19套真题
开发语言·python·计算机二级python
.简.简.单.单.2 小时前
Design Patterns In Modern C++ 中文版翻译 第十一章 享元模式
c++·设计模式·享元模式
BestOrNothing_20152 小时前
C++ 智能指针深入:四种智能指针所有权模型、原理与常见陷阱全景解析
c++·内存管理·智能指针·raii·内存销毁
huatian52 小时前
Rust 语法整理
开发语言·后端·rust
阿蔹2 小时前
Python基础语法三---函数和数据容器
开发语言·python
xingzhemengyou12 小时前
Python 多线程同步
开发语言·python