栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

线程池模型总结(基于C++11)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

线程池模型总结(基于C++11)

线程池模型总结
  • 前言

前言

线程池在初学者看起来一直是个谜一般的存在,但是理解其精髓肯定是不难的,此文就各大模型的线程池做一个简单的总结描述

此文不说明线程池的好处以及为什么使用线程池、线程池的优缺点,仅仅描述他的核心:

一个简单的线程池大概需要这几个步骤

  1. 初始化线程池
  2. 启动线程池线程
  3. 开启主循环(线程入口函数)
  4. 不断的增加任务(分配及调度线程)
  5. 销毁线程池

大致流程如下:

图中的菱形表示加锁结果的过程,运用到了C++11的unique_lock
图中的小的矩形表示条件变量的通知及阻塞,运用到了C++11的condition_variable

具体源代码如下:
xthread_pool.h

#ifndef _XTHREAD_POOL_H_
#define _XTHREAD_POOL_H_
#include 
#include 
#include 
#include 
#include 


class XTask;
class XThreadPool
{
public: 

	void Init(int num);

	void Star();

	void AddTask(XTask* task);

	XTask* GetTask();

private:
	void MainPool();

	int thread_num_ = 0;
	std::mutex mux_;
	std::vector threads_;
	std::list tasks_;
	std::condition_variable cv_;
};

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

class MyTask : public XTask
{
public:
	std::string name = "";
	int Run()
	{
		std::cout << "" << name << std::endl;
			return 0;
	}

private:

};



#endif

xthread_pool.cpp

#include "xthread_pool.h"
using namespace std;

void XThreadPool::Init(int num)
{
	unique_lock lock(mux_);
	this->thread_num_ = num;
	cout << "ThreadPool Init: " << num << endl;
}

void XThreadPool::Star()
{
	unique_lock lock(mux_);
	if (thread_num_ <= 0)
	{
		cerr << "Need Init ThreadPool"  << endl;
		return;
	}
	if (!threads_.empty())
	{
		cerr << "ThreadPool has Inited" << endl;
		return;
	}
	for (int i = 0; i < thread_num_; i++)
	{
		auto th = new thread(&XThreadPool::MainPool, this);
		threads_.push_back(th);
	}

}

void XThreadPool::AddTask(XTask* task)
{
	unique_lock lock(mux_);
	tasks_.push_back(task);
	lock.unlock();
	cv_.notify_one();
}

XTask* XThreadPool::GetTask()
{
	unique_lock lock(mux_);
	if (tasks_.empty())
	{
		cv_.wait(lock);
	}
	if (tasks_.empty()) return nullptr;

	auto task = tasks_.front();
	tasks_.pop_front();
	return task;
}

void XThreadPool::MainPool()
{
	cout << "Begin run:" << this_thread::get_id() << endl;

	while (true)
	{
		auto task = GetTask();
		if (!task) continue;
		try {
			task->Run();
		}
		catch(...){

		}
	}


	cout << "End run:" << this_thread::get_id() << endl;
}

main.cpp

#include 
#include "xthread_pool.h"

int main()
{
    XThreadPool pool;
    pool.Init(16);
    pool.Star();

    MyTask task1;
    task1.name = "001";
    
    pool.AddTask(&task1);
    getchar();
    return 0;
}

运行程序之后可以简单的查看一个线程池的分配调度结果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/457670.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号