【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++ STL-string类底层实现过程

《C++STL-string类底层实现过程》本文实现了一个简易的string类,涵盖动态数组存储、深拷贝机制、迭代器支持、容量调整、字符串修改、运算符重载等功能,模拟标准string核心特性,重点强... 目录实现框架一、默认成员函数1.默认构造函数2.构造函数3.拷贝构造函数(重点)4.赋值运算符重载函数

C++ vector越界问题的完整解决方案

《C++vector越界问题的完整解决方案》在C++开发中,std::vector作为最常用的动态数组容器,其便捷性与性能优势使其成为处理可变长度数据的首选,然而,数组越界访问始终是威胁程序稳定性的... 目录引言一、vector越界的底层原理与危害1.1 越界访问的本质原因1.2 越界访问的实际危害二、基

c++日志库log4cplus快速入门小结

《c++日志库log4cplus快速入门小结》文章浏览阅读1.1w次,点赞9次,收藏44次。本文介绍Log4cplus,一种适用于C++的线程安全日志记录API,提供灵活的日志管理和配置控制。文章涵盖... 目录简介日志等级配置文件使用关于初始化使用示例总结参考资料简介log4j 用于Java,log4c

C++归并排序代码实现示例代码

《C++归并排序代码实现示例代码》归并排序将待排序数组分成两个子数组,分别对这两个子数组进行排序,然后将排序好的子数组合并,得到排序后的数组,:本文主要介绍C++归并排序代码实现的相关资料,需要的... 目录1 算法核心思想2 代码实现3 算法时间复杂度1 算法核心思想归并排序是一种高效的排序方式,需要用

SpringBoot实现虚拟线程的方案

《SpringBoot实现虚拟线程的方案》Java19引入虚拟线程,本文就来介绍一下SpringBoot实现虚拟线程的方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录什么是虚拟线程虚拟线程和普通线程的区别SpringBoot使用虚拟线程配置@Async性能对比H

在Java中实现线程之间的数据共享的几种方式总结

《在Java中实现线程之间的数据共享的几种方式总结》在Java中实现线程间数据共享是并发编程的核心需求,但需要谨慎处理同步问题以避免竞态条件,本文通过代码示例给大家介绍了几种主要实现方式及其最佳实践,... 目录1. 共享变量与同步机制2. 轻量级通信机制3. 线程安全容器4. 线程局部变量(ThreadL

Linux线程同步/互斥过程详解

《Linux线程同步/互斥过程详解》文章讲解多线程并发访问导致竞态条件,需通过互斥锁、原子操作和条件变量实现线程安全与同步,分析死锁条件及避免方法,并介绍RAII封装技术提升资源管理效率... 目录01. 资源共享问题1.1 多线程并发访问1.2 临界区与临界资源1.3 锁的引入02. 多线程案例2.1 为

C++11范围for初始化列表auto decltype详解

《C++11范围for初始化列表autodecltype详解》C++11引入auto类型推导、decltype类型推断、统一列表初始化、范围for循环及智能指针,提升代码简洁性、类型安全与资源管理效... 目录C++11新特性1. 自动类型推导auto1.1 基本语法2. decltype3. 列表初始化3

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符

C++中detach的作用、使用场景及注意事项

《C++中detach的作用、使用场景及注意事项》关于C++中的detach,它主要涉及多线程编程中的线程管理,理解detach的作用、使用场景以及注意事项,对于写出高效、安全的多线程程序至关重要,下... 目录一、什么是join()?它的作用是什么?类比一下:二、join()的作用总结三、join()怎么