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();
}
相关推荐
肆忆_14 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星18 小时前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
端平入洛4 天前
auto有时不auto
c++
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20214 天前
信号量和信号
linux·c++
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc