您当前的位置: 首页 >  c++

令狐掌门

暂无认证

  • 0浏览

    0关注

    513博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

基于C++ 11的线程池简单实现

令狐掌门 发布时间:2021-06-20 21:58:09 ,浏览量:0

  C++11 加入了线程库,从此告别了标准库不支持并发的历史。然而 c++ 对于多线程的支持还是比较低级,稍微高级一点的用法都需要自己去实现,譬如线程池、信号量等。线程池(thread pool)这个东西,在面试上多次被问到,一般的回答都是:“管理一个任务队列,一个线程队列,然后每次取一个任务分配给一个线程去做,循环往复。” 貌似没有问题吧。但是写起程序来的时候就出问题了。

  下面给出线程池的代码   threadpool.h

#pragma once

#ifndef THREAD_POOL_H
#define THREAD_POOL_H

#include 
#include 
#include 
#include 
#include 


using namespace std;

class threadpool
{
private:
	using Task = function;	//定义线程类型
	vector _pool;           //线程池
	queue _tasks;             //任务队列
	mutex _lock;                    //同步
	condition_variable _task_cv;    //条件阻塞
	atomic _run{ true };      //线程池是否执行
	atomic  _idlThrNum{ 0 };   //空闲线程数量

public:
	inline threadpool(unsigned short size = 4) { addThread(size); }

	inline ~threadpool()
	{
		_run=false;
		_task_cv.notify_all(); // 唤醒所有线程执行

		for (thread& thread : _pool) 
		{
			if (thread.joinable())
			{
				thread.join(); // 等待任务结束, 前提:线程一定会执行完
			}
		}
	}

public:

	// 提交一个任务,调用.get()获取返回值会等待任务执行完,获取返回值
	template
	auto commit(F&& f, Args&&... args) ->future
	{
		if (!_run)    
			throw runtime_error("commit on ThreadPool is stopped.");

		using RetType = decltype(f(args...)); 
		auto task = make_shared(
			bind(forward(f), forward(args)...)
		); 

		future future = task->get_future();
		{   
			// 添加任务到队列
			lock_guard lock{ _lock };
			_tasks.emplace([task](){ 
				(*task)();
			});
		}

		_task_cv.notify_one(); // 唤醒一个线程执行

		return future;
	}

	//空闲线程数量
	int idlCount() { return _idlThrNum; }

	//线程数量
	int thrCount() { return _pool.size(); }

private:

	//添加指定数量的线程
	void addThread(unsigned short size)
	{
		//获取硬件可支持的并发线程数量
		const int thread_max_counts = std::thread::hardware_concurrency();

		for (; _pool.size()  0; --size)
		{   
			//增加线程数量,但不超过 预定义数量 thread_max_counts
			_pool.emplace_back( [this]{ //工作线程函数
				while (_run)
				{
					Task task; // 获取一个待执行的 task
					{
						unique_lock lock{ _lock };

						// wait 直到有 task
						_task_cv.wait(lock, [this]{
								return !_run || !_tasks.empty();
						}); 

						if (!_run && _tasks.empty())
							return;

						task = move(_tasks.front()); // 按先进先出从队列取一个 task
						_tasks.pop();
					}

					_idlThrNum--;
					task(); //执行任务
					_idlThrNum++;
				}
			});

			_idlThrNum++;
		}
	}
};

#endif  

  该线程池的实现全部是在头文件做的,不需要cpp文件

  main函数测试代码

#include "threadpool.h"
#include 
#include 

using namespace std;

//普通函数
void fun1(int slp)
{
	cout             
关注
打赏
1652240117
查看更多评论
0.0628s