【C++笔记】C++11实现线程池和代码解析

本文介绍了基于C++11的线程池实现,包括线程池的工作原理、代码分析,特别是C++11的新特性如lambda表达式、智能指针、模板等的应用。同时展示了如何提交任务、获取返回值以及线程池的销毁过程。代码中还包含了测试用例,展示了如何使用线程池执行不同类型的函数和任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 综述

最近看到别人写的一份基于c++11实现简单线程池(可变参数)代码,写的精简实用,且用了很多c++11以后的新特性,在此分享给大家;

1.1 线程池原理

网上已有大量关于讲解线程池原理的文章,这里不详细展开了。基本可总结为线程池一般要复用线程,一个线程 pool,具有一个线程队列 queue,一个任务队列 queue。

线程队列中的每一个 thread 都去执行调度函数:循环获取一个 task,然后执行之,保证了 thread 函数的唯一性,而且复用线程执行 task。

任务队列是典型的生产者-消费者模型,本模型至少需要两个工具:一个 mutex + 一个条件变量,或是一个 mutex + 一个信号量。mutex 实际上就是锁,保证任务的添加和移除(获取)的互斥性,一个条件变量是保证获取 task 的同步性:一个 empty 的队列,线程应该等待(阻塞);

1.2 代码分析(c++11之后新特性)

(1)pool.emplace_back( [this]{…} ) 和 pool.push_back( [this]{…} ) 功能一样,只不过前者性能会更好,减少了临时copy的消耗;pool.emplace_back( [this]{…} ) 是构造了一个线程对象,执行函数是 lambda 匿名函数 ;

(2) 匿名函数[this]{…} ,[] 是捕捉器,this 是引用域外的变量 this指针, 内部使用死循环, 由cv_task.wait( lock, [this]{…} ) 来阻塞线程;

(3)delctype(expr) 用来推断 expr 的类型,和 auto 是类似的,相当于类型占位符,占据一个类型的位置;auto f(A a, B b) -> decltype(a+b) 是一种用法;

(4)commit 成员函数,可以带任意多的参数,第一个参数是 f,后面依次是函数 f 的参数!( 注意:参数要传 struct / class 的话,建议用pointer,小心变量的作用域 ) 可变参数模板是 c++11 的一大亮点,至于为什么是 Arg… 和 arg… ,因为规定就是这么用的!

(5)commit 直接使用只能调用 stdcall 函数,但有两种方法可以实现调用类成员,一种是使用 bind:commit( std::bind( &Dog::sayHello, &dog) ); 一种是用 mem_fn:commit( std::mem_fn(&Dog::sayHello), &dog );

(6)make_shared 用来构造 shared_ptr 智能指针。用法大体是 shared_ptr p = make_shared(4) 然后 *p == 4 。智能指针可以自动释放资源;

(7)bind 函数,接受函数 f 和部分参数,返回currying后的匿名函数,譬如 bind(add, 4) 可以实现类似 add(4)的函数;

(8)forward() 函数,类似于 move() 函数,后者是将参数右值化,前者是是不改变最初传入的类型的引用类型(左值还是左值,右值还是右值);

(9)packaged_task 就是任务函数的封装类,通过 get_future 获取 future , 然后通过 future 可以获取函数的返回值( future.get() );packaged_task 本身可以像函数一样调用 () ;

(10)queue 是队列类, front() 获取头部元素, pop() 移除头部元素;back() 获取尾部元素,push() 尾部添加元素;当有任务优先级时,也可以使用priority_queue() ;

(11)lock_guard 是 mutex 的 stack 封装类,构造的时候 lock(),析构的时候 unlock(),是 c++ RAII 的 idea;但目前使用 uinque_lock() 的较多,因为相比lock_guard(),功能更多;

(12)condition_variable cv是条件变量,需要配合 unique_lock 使用;unique_lock 相比 lock_guard 的好处是:可以随时 unlock() 和 lock()。 cv.wait() 之前需要持有 mutex,wait 本身会 unlock() mutex,如果条件满足则会重新持有 mutex;

(13)atomic 本身是原子类型,操作 load()/store() 是原子操作,所以不需要再加 mutex;

1.3 源代码

1.3.1 threadPool.h

#pragma once
#ifndef THREAD_POOL_H
#define THREAD_POOL_H

#include <vector>
#include <queue>
#include <atomic>
#include <future>
#include <condition_variable>
#include <thread>
#include <functional>
#include <stdexcept>

namespace std
{
//线程池最大容量,应尽量设小一点
#define  THREADPOOL_MAX_NUM 16
//#define  THREADPOOL_AUTO_GROW

//线程池,可以提交变参函数或lambda表达式的匿名函数执行,可以获取执行返回值
//不直接支持类成员函数, 支持类静态成员函数或全局函数,Opteron()函数等
	class threadpool
	{
		using Task = function<void()>;	//定义类型
		vector<thread> _pool;           //线程池
		queue<Task> _tasks;             //任务队列
		mutex _lock;                    //同步
		condition_variable _task_cv;    //条件阻塞
		atomic<bool> _run{ true };      //线程池是否执行
		atomic<int>  _idlThrNum{ 0 };   //空闲线程数量

	public:
		inline threadpool(unsigned short size = 4) { addThread(size); }
		
		inline ~threadpool(){
			_run = false;
			_task_cv.notify_all(); 
			for (thread& thread : _pool) {
				//thread.detach(); // 让线程“自生自灭”
				if (thread.joinable())
					thread.join(); // 等待任务结束, 前提:线程一定会执行完
			}
		}

	public:
		// 提交一个任务
		// 调用.get()获取返回值会等待任务执行完,获取返回值
		// 有两种方法可以实现调用类成员,
		// 一种是使用   bind: .commit(std::bind(&Dog::sayHello, &dog));
		// 一种是用   mem_fn: .commit(std::mem_fn(&Dog::sayHello), this)
		template<class F, class... Args>
		auto commit(F&& f, Args&&... args) ->future<decltype(f(args...))>
		{
			if (!_run)    // stoped ??
				throw runtime_error("commit on ThreadPool is stopped.");

			using RetType = decltype(f(args...));  // typename std::result_of<F(Args...)>::type, 函数 f 的返回值类型
			// 把函数入口及参数,打包(绑定)
			auto task = make_shared<packaged_task<RetType()>>( bind(forward<F>(f), forward<Args>(args)...)); 
			future<RetType> future = task->get_future();
			{    // 添加任务到队列
				lock_guard<mutex> lock{ _lock };
				_tasks.emplace([task]() { (*task)();} );
			}

#ifdef THREADPOOL_AUTO_GROW
			if (_idlThrNum < 1 && _pool.size() < THREADPOOL_MAX_NUM)
				addThread(1);
#endif // !THREADPOOL_AUTO_GROW
			_task_cv.notify_one(); // 唤醒一个线程执行
			return future;
		}
		//空闲线程数量
		int idlCount() { return _idlThrNum; }
		//线程数量
		int thrCount() { return _pool.size(); }

#ifndef THREADPOOL_AUTO_GROW
	private:
#endif // !THREADPOOL_AUTO_GROW
		
		//添加指定数量的线程
		void addThread(unsigned short size){
			for (; _pool.size() < THREADPOOL_MAX_NUM && size > 0; --size)
			{   //增加线程数量,但不超过 预定义数量 THREADPOOL_MAX_NUM
				_pool.emplace_back([this] { //工作线程函数
					while (_run){
						Task task; // 获取一个待执行的 task
						{
							// unique_lock 相比 lock_guard 的好处是:可以随时 unlock() 和 lock()
							unique_lock<mutex> lock{ _lock };
							_task_cv.wait(lock, [this] {return !_run || !_tasks.empty();}); // wait 直到有 task
							if (!_run && _tasks.empty())
								return;

							task = move(_tasks.front()); // 按先进先出从队列取一个 task
							_tasks.pop();
						}
						_idlThrNum--;
						task();//执行任务
						_idlThrNum++;
					}
				});
				_idlThrNum++;
			}
		}
	};
}

#endif

1.3.2 测试代码example.h


void fun1(int slp){
	printf("  hello, fun1 !  %d\n", std::this_thread::get_id());
	if (slp > 0) {
		printf(" ======= fun1 sleep %d  =========  %d\n", slp, std::this_thread::get_id());
		std::this_thread::sleep_for(std::chrono::milliseconds(slp));
		//Sleep(slp );
	}
}

struct gfun {
	int operator()(int n) {
		std::cout << "hello, gfun ! " << n << "   " << std::this_thread::get_id();
		return 42;
	}
};

class A {    
public:
	static int Afun(int n = 0) {
		std::cout <<"hello, Afun !  " << " param: " << n
			<< std::this_thread::get_id() << std::endl;
		return n;
	}

	static std::string Bfun(int n, std::string str, char c) {
		std::cout << n << "  hello, Bfun !  param: " << str.c_str() 
			<< "  " << (int)c << "  " << std::this_thread::get_id() << std::endl;
		return str;
	}
};

int myfun1(int num){
	std::cout << std::this_thread::get_id() <<"  "<< __FUNCTION__ << std::endl;
	std::this_thread::sleep_for(std::chrono::seconds(num));
	return (num * num);
}

int myfun2(int num1, int num2){
	std::cout << std::this_thread::get_id() << "  " << __FUNCTION__ << std::endl;
	std::this_thread::sleep_for(std::chrono::seconds(num1));
	return (num1 + num2);
}

int  main()
{
	std::threadpool mypool{ 5 };
	std::future<int> f_fun1 = mypool.commit(myfun1, 5);
	std::future<int> f_fun2 = mypool.commit(myfun2, 1, 2);
	std::future<int> f_gfun = mypool.commit(gfun{}, 0);
	std::future<int> f_afun = mypool.commit(A::Afun, 9999); 
	std::future<std::string> f_bfun = mypool.commit(A::Bfun, 9998, "mult args", 123);
	std::future<std::string> f_lambda = mypool.commit([]()->std::string { std::cout << "hello, fh !  " 
								<< std::this_thread::get_id() << std::endl; return "hello,fh ret !"; });

	std::cout <<"idlCount: "<< mypool.idlCount() << std::endl;
	std::cout <<"thrCount: "<< mypool.thrCount() << std::endl;
	std::cout << f_fun1.get() << std::endl;
	std::cout << f_fun11.get() << std::endl;
	std::cout << f_fun2.get() << std::endl;
	std::cout << f_gfun.get() << std::endl;
	std::cout << f_afun.get() << std::endl;
	std::cout << f_bfun.get().c_str() << std::endl;
	std::cout << f_lambda.get().c_str() << std::endl;
	return 0;
}

2 参考文献

1、c++11线程池实现
2、基于C++11的线程池(threadpool),简洁且可以带任意多的参数
3、https://github.com/progschj/ThreadPool

学习 C++,任重而道远!!!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值