【C++】基于C++11的线程池:threadpool

2024-01-02 22:12
文章标签 c++ 线程 threadpool

本文主要是介绍【C++】基于C++11的线程池:threadpool,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1、参考

作者博客:https://www.cnblogs.com/lzpong/p/6397997.html
源码:https://github.com/lzpong/threadpool

2、源码

原理:利用生产者-消费者模型,管理一个任务队列,一个线程队列,然后每次取一个任务分配给一个线程去做,循环往复。

#pragma once
#ifndef THREAD_POOL_H
#define THREAD_POOL_H#include <vector>
#include <queue>
#include <atomic>
#include <future>
#include <stdexcept>namespace std
{
//线程池最大容量,应尽量设小一点
#define  THREADPOOL_MAX_NUM 16
//线程池是否可以自动增长(如果需要,且不超过 THREADPOOL_MAX_NUM)
//#define  THREADPOOL_AUTO_GROW//线程池,可以提交变参函数或拉姆达表达式的匿名函数执行,可以获取执行返回值
//不直接支持类成员函数, 支持类静态成员函数或全局函数,Opteron()函数等
class threadpool
{unsigned short _initSize;       //初始化线程数量using Task = function<void()>; //定义类型vector<thread> _pool;          //线程池queue<Task> _tasks;            //任务队列mutex _lock;                   //任务队列同步锁
#ifdef THREADPOOL_AUTO_GROWmutex _lockGrow;               //线程池增长同步锁
#endif // !THREADPOOL_AUTO_GROWcondition_variable _task_cv;   //条件阻塞atomic<bool> _run{ true };     //线程池是否执行atomic<int>  _idlThrNum{ 0 };  //空闲线程数量public:inline threadpool(unsigned short size = 4) { _initSize = size; 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 };//对当前块的语句加锁  lock_guard 是 mutex 的 stack 封装类,构造的时候 lock(),析构的时候 unlock()_tasks.emplace([task]() { // push(Task{...}) 放到队列后面(*task)();});}
#ifdef THREADPOOL_AUTO_GROWif (_idlThrNum < 1 && _pool.size() < THREADPOOL_MAX_NUM)addThread(1);
#endif // !THREADPOOL_AUTO_GROW_task_cv.notify_one(); // 唤醒一个线程执行return future;}// 提交一个无参任务, 且无返回值template <class F>void commit2(F&& task){if (!_run) return;{lock_guard<mutex> lock{ _lock };_tasks.emplace(std::forward<F>(task));}
#ifdef THREADPOOL_AUTO_GROWif (_idlThrNum < 1 && _pool.size() < THREADPOOL_MAX_NUM)addThread(1);
#endif // !THREADPOOL_AUTO_GROW_task_cv.notify_one();}//空闲线程数量int idlCount() { return _idlThrNum; }//线程数量int thrCount() { return _pool.size(); }#ifndef THREADPOOL_AUTO_GROW
private:
#endif // !THREADPOOL_AUTO_GROW//添加指定数量的线程void addThread(unsigned short size){
#ifdef THREADPOOL_AUTO_GROWif (!_run)    // stoped ??throw runtime_error("Grow on ThreadPool is stopped.");unique_lock<mutex> lockGrow{ _lockGrow }; //自动增长锁
#endif // !THREADPOOL_AUTO_GROWfor (; _pool.size() < THREADPOOL_MAX_NUM && size > 0; --size){   //增加线程数量,但不超过 预定义数量 THREADPOOL_MAX_NUM_pool.emplace_back( [this]{ //工作线程函数while (true) //防止 _run==false 时立即结束,此时任务队列可能不为空{Task task; // 获取一个待执行的 task{// unique_lock 相比 lock_guard 的好处是:可以随时 unlock() 和 lock()unique_lock<mutex> lock{ _lock };_task_cv.wait(lock, [this] { // wait 直到有 task, 或需要停止return !_run || !_tasks.empty();});if (!_run && _tasks.empty())return;_idlThrNum--;task = move(_tasks.front()); // 按先进先出从队列取一个 task_tasks.pop();}task();//执行任务
#ifdef THREADPOOL_AUTO_GROWif (_idlThrNum>0 && _pool.size() > _initSize) //支持自动释放空闲线程,避免峰值过后大量空闲线程return;
#endif // !THREADPOOL_AUTO_GROW{unique_lock<mutex> lock{ _lock };_idlThrNum++;}}});{unique_lock<mutex> lock{ _lock };_idlThrNum++;}}}
};
}
#endif  //https://github.com/lzpong/

3、涉及的C++11的知识

1)using Task = function<void()> 是类型别名,简化了 typedef 的用法。function<void()> 可以认为是一个函数类型,接受任意原型是 void() 的函数,或是函数对象,或是匿名函数。void() 意思是不带参数,没有返回值。

2)pool.emplace_back([this]{…}) 和 pool.push_back([this]{…}) 功能一样,只不过前者性能会更好;

3)pool.emplace_back([this]{…}) 是构造了一个线程对象,执行函数是拉姆达匿名函数 ;

4)所有对象的初始化方式均采用了 {},而不再使用 () 方式,因为风格不够一致且容易出错;

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

6)delctype(expr) 用来推断 expr 的类型,和 auto 是类似的,相当于类型占位符,占据一个类型的位置;auto f(A a, B b) -> decltype(a+b) 是一种用法,不能写作 decltype(a+b) f(A a, B b),为啥?! c++ 就是这么规定的!

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

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

9)make_shared 用来构造 shared_ptr 智能指针。用法大体是 shared_ptr p = make_shared(4) 然后 *p == 4 。智能指针的好处就是, 自动 delete !

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

11)forward() 函数,类似于 move() 函数,后者是将参数右值化,前者是… 肿么说呢?大概意思就是:不改变最初传入的类型的引用类型(左值还是左值,右值还是右值);

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

13)queue 是队列类, front() 获取头部元素, pop() 移除头部元素;back() 获取尾部元素,push() 尾部添加元素;

14)lock_guard 是 mutex 的 stack 封装类,构造的时候 lock(),析构的时候 unlock(),是 c++ RAII 的 idea;

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

16)最后线程池析构的时候,join() 可以等待任务都执行完在结束,很安全!

4、使用demo

#include "threadpool.h"
#include <iostream>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));}
}struct gfun {int operator()(int n) {printf("%d  hello, gfun !  %d\n" ,n, std::this_thread::get_id() );return 42;}
};class A {
public:static int Afun(int n = 0) {   //函数必须是 static 的才能直接使用线程池std::cout << n << "  hello, Afun !  " << 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 !  "<< str.c_str() <<"  " << (int)c <<"  " << std::this_thread::get_id() << std::endl;return str;}
};int main()try {std::threadpool executor{ 50 };A a;std::future<void> ff = executor.commit(fun1,0);std::future<int> fg = executor.commit(gfun{},0);std::future<int> gg = executor.commit(a.Afun, 9999); //IDE提示错误,但可以编译运行std::future<std::string> gh = executor.commit(A::Bfun, 9998,"mult args", 123);std::future<std::string> fh = executor.commit([]()->std::string { std::cout << "hello, fh !  " << std::this_thread::get_id() << std::endl; return "hello,fh ret !"; });std::cout << " =======  sleep ========= " << std::this_thread::get_id() << std::endl;std::this_thread::sleep_for(std::chrono::microseconds(900));for (int i = 0; i < 50; i++) {executor.commit(fun1,i*100 );}std::cout << " =======  commit all ========= " << std::this_thread::get_id()<< " idlsize="<<executor.idlCount() << std::endl;std::cout << " =======  sleep ========= " << std::this_thread::get_id() << std::endl;std::this_thread::sleep_for(std::chrono::seconds(3));ff.get(); //调用.get()获取返回值会等待线程执行完,获取返回值std::cout << fg.get() << "  " << fh.get().c_str()<< "  " << std::this_thread::get_id() << std::endl;std::cout << " =======  sleep ========= " << std::this_thread::get_id() << std::endl;std::this_thread::sleep_for(std::chrono::seconds(3));std::cout << " =======  fun1,55 ========= " << std::this_thread::get_id() << std::endl;executor.commit(fun1,55).get();    //调用.get()获取返回值会等待线程执行完std::cout << "end... " << std::this_thread::get_id() << std::endl;std::threadpool pool(4);std::vector< std::future<int> > results;for (int i = 0; i < 8; ++i) {results.emplace_back(pool.commit([i] {std::cout << "hello " << i << std::endl;std::this_thread::sleep_for(std::chrono::seconds(1));std::cout << "world " << i << std::endl;return i*i;}));}std::cout << " =======  commit all2 ========= " << std::this_thread::get_id() << std::endl;for (auto && result : results)std::cout << result.get() << ' ';std::cout << std::endl;return 0;}
catch (std::exception& e) {std::cout << "some unhappy happened...  " << std::this_thread::get_id() << e.what() << std::endl;
}

这篇关于【C++】基于C++11的线程池:threadpool的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/563784

相关文章

C++实现回文串判断的两种高效方法

《C++实现回文串判断的两种高效方法》文章介绍了两种判断回文串的方法:解法一通过创建新字符串来处理,解法二在原字符串上直接筛选判断,两种方法都使用了双指针法,文中通过代码示例讲解的非常详细,需要的朋友... 目录一、问题描述示例二、解法一:将字母数字连接到新的 string思路代码实现代码解释复杂度分析三、

Spring Boot 中正确地在异步线程中使用 HttpServletRequest的方法

《SpringBoot中正确地在异步线程中使用HttpServletRequest的方法》文章讨论了在SpringBoot中如何在异步线程中正确使用HttpServletRequest的问题,... 目录前言一、问题的来源:为什么异步线程中无法访问 HttpServletRequest?1. 请求上下文与线

在 Spring Boot 中使用异步线程时的 HttpServletRequest 复用问题记录

《在SpringBoot中使用异步线程时的HttpServletRequest复用问题记录》文章讨论了在SpringBoot中使用异步线程时,由于HttpServletRequest复用导致... 目录一、问题描述:异步线程操作导致请求复用时 Cookie 解析失败1. 场景背景2. 问题根源二、问题详细分

C++一个数组赋值给另一个数组方式

《C++一个数组赋值给另一个数组方式》文章介绍了三种在C++中将一个数组赋值给另一个数组的方法:使用循环逐个元素赋值、使用标准库函数std::copy或std::memcpy以及使用标准库容器,每种方... 目录C++一个数组赋值给另一个数组循环遍历赋值使用标准库中的函数 std::copy 或 std::

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

C++初始化数组的几种常见方法(简单易懂)

《C++初始化数组的几种常见方法(简单易懂)》本文介绍了C++中数组的初始化方法,包括一维数组和二维数组的初始化,以及用new动态初始化数组,在C++11及以上版本中,还提供了使用std::array... 目录1、初始化一维数组1.1、使用列表初始化(推荐方式)1.2、初始化部分列表1.3、使用std::

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没

Java多线程父线程向子线程传值问题及解决

《Java多线程父线程向子线程传值问题及解决》文章总结了5种解决父子之间数据传递困扰的解决方案,包括ThreadLocal+TaskDecorator、UserUtils、CustomTaskDeco... 目录1 背景2 ThreadLocal+TaskDecorator3 RequestContextH

java父子线程之间实现共享传递数据

《java父子线程之间实现共享传递数据》本文介绍了Java中父子线程间共享传递数据的几种方法,包括ThreadLocal变量、并发集合和内存队列或消息队列,并提醒注意并发安全问题... 目录通过 ThreadLocal 变量共享数据通过并发集合共享数据通过内存队列或消息队列共享数据注意并发安全问题总结在 J