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();
}
相关推荐
清酒难咽3 小时前
算法案例之递归
c++·经验分享·算法
Rabbit_QL3 小时前
【水印添加工具】从零设计一个工程级 Python 图片水印工具:WaterMask 架构与实现
开发语言·python
天“码”行空3 小时前
简化Lambda——方法引用
java·开发语言
z20348315203 小时前
C++对象布局
开发语言·c++
Beginner x_u3 小时前
如何解释JavaScript 中 this 的值?
开发语言·前端·javascript·this 指针
java1234_小锋4 小时前
Java线程之间是如何通信的?
java·开发语言
张张努力变强4 小时前
C++ Date日期类的设计与实现全解析
java·开发语言·c++·算法
沉默-_-4 小时前
力扣hot100滑动窗口(C++)
数据结构·c++·学习·算法·滑动窗口
feifeigo1234 小时前
基于EM算法的混合Copula MATLAB实现
开发语言·算法·matlab
LYS_06184 小时前
RM赛事C型板九轴IMU解算(4)(卡尔曼滤波)
c语言·开发语言·前端·卡尔曼滤波