IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> C++知识库 -> 基于C++11 的线程池 -> 正文阅读

[C++知识库]基于C++11 的线程池

本章主要将基于C++11实现的线程池,暂时没有考虑线程的动态申请和注销(可以根据自己需求实现)。线程数量值建议:cpu核数*2+1。线程过多会导致线程切换浪费大量资源,线程数量过少可能导致并发性能下降。

ThreadPool.h

#pragma once
#include <memory>
#include <queue>
#include <vector>
#include <atomic>
#include <thread>
#include <condition_variable>
namespace Jef{

	class ITask{
	public:
		virtual ~ITask(){};
		virtual void run() = 0;
	};

	class Semaphore{
	public:
		Semaphore(unsigned long init_sem = 0);

		bool wait(int wait_milliseconds = 0x7fffffff);
		void signal();
	private:
		std::mutex _mtx;
		std::condition_variable _cond;
		unsigned long _count;
	};


	class ThreadPool
	{
	public:
		ThreadPool(int thread_num);
		virtual ~ThreadPool();
		virtual void on_idle();

		void start();
		void stop();
		void addTask(std::shared_ptr<ITask> task);
	protected:
		std::shared_ptr<ITask> pop_task();
		void add_thread();
		
		void release_thread();
		void _run();
	private:
		Semaphore _sem;
		int _thread_num;
		std::mutex _mtx;
		std::atomic_bool _is_exit;
		std::queue<std::shared_ptr<ITask> > _task;
		std::vector<std::thread> _threads;
	};
};

ThreadPool.cpp

#include "stdafx.h"
#include "ThreadPool.h"
#include <iostream>

namespace Jef{
	///
	Semaphore::Semaphore(unsigned long init_sem){
		_count = init_sem;
	}

	bool Semaphore::wait(int wait_milliseconds)
	{
		std::unique_lock<std::mutex> lk(_mtx);
		if (_cond.wait_for(lk, std::chrono::milliseconds(wait_milliseconds), [&](){return _count > 0; }))
		{
			--_count;
			return true;
		}
		return false;
	}

	void Semaphore::signal()
	{
		std::unique_lock<std::mutex> lk(_mtx);
		++_count;
		_cond.notify_one();
	}

	///
	ThreadPool::ThreadPool(int thread_num)
	{
		_thread_num = thread_num;
		_is_exit = false;
	}


	ThreadPool::~ThreadPool()
	{
		stop();
	}

	void ThreadPool::start()
	{
		for (int i = 0; i < _thread_num; ++i)
		{
			add_thread();
		}
	}

	void ThreadPool::stop()
	{
		_is_exit = true;
		for (auto &it : _threads)
		{
			if (it.joinable())
			{
				it.join();
			}
		}
	}

	void ThreadPool::addTask(std::shared_ptr<ITask> task)
	{
		{
			std::lock_guard<std::mutex> lk(_mtx);
			_task.push(task);
		}
		_sem.signal();
	}

	std::shared_ptr<ITask> ThreadPool::pop_task()
	{
		std::shared_ptr<ITask> task = nullptr;
		std::lock_guard<std::mutex> lk(_mtx);
		if (!_task.empty())
		{
			task = _task.front();
			_task.pop();
		}
		return task;
	}

	void ThreadPool::add_thread()
	{
		std::thread t = std::thread(std::bind(&Jef::ThreadPool::_run, this));
		_threads.push_back(std::move(t));
	}

	void ThreadPool::release_thread()
	{
		
	}

	void ThreadPool::_run()
	{
		while (!_is_exit)
		{
			if (_sem.wait(100))
			{
				std::shared_ptr<ITask> task = pop_task();
				if (task != nullptr)
				{
					task->run();
				}

			}
			else
			{
				on_idle();
			}
		}

		std::ostringstream oss;
		oss << std::this_thread::get_id();
		std::string stid = oss.str();
		unsigned long long tid = std::stoull(stid);
		LOG_INFO_F(_T("thread:[%I64d] exit"), tid);
	}

	void ThreadPool::on_idle()
	{
		std::ostringstream oss;
		oss << std::this_thread::get_id();
		std::string stid = oss.str();
		unsigned long long tid = std::stoull(stid);
		LOG_INFO_F(_T("thread:[%I64d] on_idle"), tid);
	}
}

基本使用:

//任务继承ITask,在run里面实现业务逻辑
//如果想在线程空闲的时候处理某些业务,可以重写ThreadPool的OnIdle函数
class TaskA :public Jef::ITask{
public:
	TaskA(){

	}
	TaskA(int a, int b)
	{
		this->a = a;
		this->b = b;
	}
	virtual void run(){
		cout << a << "----" << b << "---" << "TaskA" << endl;
	}

private:
	int a;
	int b;
};


//启动线程池
Jef::ThreadPool pool(4);
pool.start()

//添加任务
pool.addTask(shared_ptr<TaskA>(new TaskA(a, i)));
  C++知识库 最新文章
【C++】友元、嵌套类、异常、RTTI、类型转换
通讯录的思路与实现(C语言)
C++PrimerPlus 第七章 函数-C++的编程模块(
Problem C: 算法9-9~9-12:平衡二叉树的基本
MSVC C++ UTF-8编程
C++进阶 多态原理
简单string类c++实现
我的年度总结
【C语言】以深厚地基筑伟岸高楼-基础篇(六
c语言常见错误合集
上一篇文章      下一篇文章      查看所有文章
加:2022-05-01 15:31:12  更:2022-05-01 15:33:05 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/21 4:48:38-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码