c++ 线程池/Github 开源项目源码分析(progschj/ThreadPool)

news/2024/7/10 19:43:47 标签: c++, github, 开源

c++ 线程池/Github 开源项目源码分析(progschj/ThreadPool)

  • 前言
  • [ThreadPool 项目地址](https://github.com/progschj/ThreadPool)
  • 项目源码:
  • 基本用法
  • 类成员变量
  • 类成员函数
    • 构造函数的签名
    • 创建线程
    • 线程默认的任务
    • 向任务队列中添加一个任务
    • 析构函数
  • 总结

前言

维基百科上对线程池的简要介绍:

线程池(thread pool):一种线程使用模式。线程过多会带来调度开销,进而影响缓存局部性和整体性能。而线程池维护着多个线程,等待着监督管理者分配可并发执行的任务。这避免了在处理短时间任务时创建与销毁线程的代价。线程池不仅能够保证内核的充分利用,还能防止过分调度。可用线程数量应该取决于可用的并发处理器、处理器内核、内存、网络sockets等的数量。

github.com/progschj/ThreadPool">ThreadPool 项目地址

progschj/ThreadPool 是一个简易的基于 c++11 标准的线程池实现,采用了 Zlib license(相当宽松自由的开源协议,任意修改分发商用),截止当前时间点,已获得 7k+ stars。整个项目源码仅有一个头文件,代码行数不足一百行,早在多年前就已稳定不再更新。

项目源码:

#ifndef THREAD_POOL_H
#define THREAD_POOL_H

#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>

class ThreadPool {
public:
    ThreadPool(size_t);
    template<class F, class... Args>
    auto enqueue(F&& f, Args&&... args)
        -> std::future<typename std::result_of<F(Args...)>::type>;
    ~ThreadPool();
private:
    // need to keep track of threads so we can join them
    std::vector< std::thread > workers;
    // the task queue
    std::queue< std::function<void()> > tasks;

    // synchronization
    std::mutex queue_mutex;
    std::condition_variable condition;
    bool stop;
};

// the constructor just launches some amount of workers
inline ThreadPool::ThreadPool(size_t threads)
    : stop(false)
{
    for (size_t i = 0; i < threads; ++i)
        workers.emplace_back(
            [this]
            {
                for (;;)
                {
                    std::function<void()> task;
                    
                    {
                        std::unique_lock<std::mutex> lock(this->queue_mutex);
                        this->condition.wait(lock, [this] 
                        { 
                            return this->stop || !this->tasks.empty(); 
                        });

                        if (this->stop && this->tasks.empty())
                            return;

                        task = std::move(this->tasks.front());
                        this->tasks.pop();
                    }

                    task();
                }
            }
    );
}

// add new work item to the pool
template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>
{
    using return_type = typename std::result_of<F(Args...)>::type;

    auto task = std::make_shared< std::packaged_task<return_type()> >(
        std::bind(std::forward<F>(f), std::forward<Args>(args)...)
    );

    std::future<return_type> res = task->get_future();
    {
        std::unique_lock<std::mutex> lock(queue_mutex);

        // don't allow enqueueing after stopping the pool
        if (stop)
            throw std::runtime_error("enqueue on stopped ThreadPool");

        tasks.emplace([task]() { (*task)(); });
    }
    condition.notify_one();
    return res;
}

// the destructor joins all threads
inline ThreadPool::~ThreadPool()
{
    {
        std::unique_lock<std::mutex> lock(queue_mutex);
        stop = true;
    }
    condition.notify_all();
    for (std::thread& worker : workers)
        worker.join();
}

#endif

基本用法

// create thread pool with 4 worker threads
ThreadPool pool(4);

// enqueue and store future
auto result = pool.enqueue([](int answer) { return answer; }, 42);

// get result from future
std::cout << result.get() << std::endl;

类成员变量

std::vector< std::thread > workers;
std::queue< std::function<void()> > tasks;
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
  • workers:存储线程池中 std::thread 的容器
  • tasks:任务队列
  • queue_mutex:任务队列的互斥锁
  • condition:任务队列的条件变量
  • stop:线程池是否停止的标志位

类成员函数

构造函数的签名

inline ThreadPool::ThreadPool(size_t threads)
    : stop(false)
  • 构造函数传入一个 size_t 类型的参数,初始化线程池中线程的数量
  • 初始化列表将 stop 标志位初始化为 false

创建线程

for (size_t i = 0; i < threads; ++i)
{
    workers.emplace_back(
        [this]
        {
            for (;;)
            {
                //...
            }
        }
    );
}
  • 使用 for 循环创建 threads 个线程,将线程加入 workers 容器
  • lambda 表达式用于创建线程,捕获 this,lambda 表达式中包含一个无限循环

线程默认的任务

std::function<void()> task;

{
    std::unique_lock<std::mutex> lock(this->queue_mutex);
    this->condition.wait(lock, [this] 
    { 
        return this->stop || !this->tasks.empty(); 
    });

    if (this->stop && this->tasks.empty())
        return;

    task = std::move(this->tasks.front());
    this->tasks.pop();
}

task();
  • 首先声明了一个 std::function<void()> 类型的变量 task
  • 在互斥锁保护任务队列后,调用 condition.wait() 等待任务队列非空或线程池停止,线程创建后,会在这里等待;如果 stop 标志位为 true 或者任务队列不为空,解除等待,继续往下执行
  • 如果标志位 stop 为 true,且任务队列为空,此任务将退出
  • 以上条件都通过后,将从任务队列中取出一个任务 task,移动到局部变量 task 中(吐槽下:距离 c++11 标准的发布已经过去了十几年,现在还不明白这一条的,就很难评价了)
  • 执行 task(),也就是上一步从队列头部取出的任务

向任务队列中添加一个任务

template<class F, class... Args>
auto enqueue(F&& f, Args&&... args)
    -> std::future<typename std::result_of<F(Args...)>::type>;
  • enqueue 函数模板,用于任务的入队列
  • F&& f,这里预期是一个任意的 callable 对象
  • Args&&... args,一个可变模板参数,会在编译期展开参数包
  • 返回值是一个 std::future 类型的对象,用于获取任务的执行结果,std::future 的模板参数使用 std::result_of 萃取可调用对象的返回值类型
  • 注意,c++17 后 std::result_of 就已经是 deprecated,可以使用 std::invoke_result 类型萃取

继续往下看 enqueue 函数的实现:

using return_type = typename std::result_of<F(Args...)>::type;
  • 使用 std::result_of 类型萃取可调用对象的返回值类型,并使用 using 为其起个别名 reture_type
auto task = std::make_shared< std::packaged_task<return_type()> >(
    std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);

这一段做了好几件事,一步一步拆解:

  • std::make_shared 构建一个 std::shared_ptr
  • std::packaged_task 模板是用于包装 callable 对象,使用了前面推导出的 return_type 类型来实例化模板
  • std::make_shared 需要调用实例类型的构造函数,而 std::packaged_task 的构造函数需要一个可调用对象,所以这里使用 std::bind 将可变模板参数绑定给 f(对 std::bind 不熟悉的建议先行查阅资料),std::forward 转发一下类型
  • 简单来说,以上只是构建一个 callable 对象的包装器
std::future<return_type> res = task->get_future();
{
    std::unique_lock<std::mutex> lock(queue_mutex);

    // don't allow enqueueing after stopping the pool
    if (stop)
        throw std::runtime_error("enqueue on stopped ThreadPool");

    tasks.emplace([task]() { (*task)(); });
}
condition.notify_one();
return res;
  • 从 task 中获取 std::future 对象
  • 使用大括号控制代码块,在这个代码块中上锁
  • 如果线程池已经停止,抛出异常
  • 否则正常执行,将 task 推入到队列尾部
  • 条件变量通知一个等待的线程,这个时候,构造函数中 condition.wait() 会被唤醒,以执行后面的代码块,即从队列头部取出一个任务并执行
  • 最后返回 std::future 对象

析构函数

遵循 RAII 原则,释放所有资源

{
    std::unique_lock<std::mutex> lock(queue_mutex);
    stop = true;
}
condition.notify_all();
for (std::thread& worker : workers)
    worker.join();
  • 上锁,将停止标志位置为 true
  • 通知所有等待的线程
  • 等待所有线程终止

总结

该项目仅是一个线程池的简易实现,对学习 c++11 标准的多线程及部分特性有一定帮助,如果想要更复杂的具有各种调度策略的线程池,还需进一步细化。


http://www.niftyadmin.cn/n/5447571.html

相关文章

智能新纪元:AI大模型学习的奥秘与挑战

在当前技术环境下&#xff0c;AI大模型学习不仅要求研究者具备深厚的数学基础和编程能力&#xff0c;还需要对特定领域的业务场景有深入的了解。通过不断优化模型结构和算法&#xff0c;AI大模型学习能够不断提升模型的准确性和效率&#xff0c;为人类生活和工作带来更多便利。…

Python的re模块进行正则表达式操作时的常用方法[回顾学习]

re 模块是 Python 中用于处理正则表达式的标准库模块。通过 re 模块&#xff0c;可进行字符串匹配、搜索和替换等各种操作。 有几个常用的方法&#xff1a;# re.match(pattern, string)&#xff1a;从字符串开头开始匹配模式&#xff0c;并返回匹配对象。适合用于确定字符串是否…

ChatGPT智能聊天系统源码v2.7.6全开源Vue前后端+后端PHP

测试环境:Linux系统CentOS7.6、宝塔、PHP7.4、MySQL5.6,根目录public,伪静态thinkPHP,开启ssl证书 具有文章改写、广告营销文案、编程助手、办公达人、知心好友、家庭助手、出行助手、社交平台内容、视频脚本创作、AI绘画、思维导图等功能 ai通道:文心一言、MiniMax、智…

Mongodb入门到入土,安装到实战,外包半年学习的成果

这是我参与「第四届青训营 」笔记创作活动的的第27天&#xff0c;今天主要记录前端进阶必须掌握内容Mongodb数据库,从搭建环境到运行数据库,然后使用MongodB; 一、文章内容 数据库基础知识关系型数据库和非关系型数据库为什么学习Mongodb数据库环境搭建及运行MongodbMongodb命…

【VSTO开发】遍历 Ribbon 中的所有控件或按钮

在 VSTO&#xff08;Visual Studio Tools for Office&#xff09;中&#xff0c;可以通过代码来遍历 Ribbon 中的所有控件或按钮。可以使用 C# 或 VB.NET 等编程语言来实现这个功能。 下面是一个简单的示例代码&#xff0c;演示如何遍历 Ribbon 中的所有控件或按钮&#xff1a…

大数据扩展

层面控制点四级三级二级 安全 物理 环境 基础 设施 位置 应保证承载大数据存储、处理和分析的设备机房位于中国境内。应保证承载大数据存储、处理和分析的设备机房位于中国境内。应保证承载大数据存储、处理和分析的设备机房位于中国境内。安全 通信 网络网络 架构b)应保证大数…

【史上最详细教程】数据分析三剑客之numpy

目录 一、numpy模块介绍 二、环境搭建 三、numpy创建数组 3.1 创建一维数组 3.2 创建二维数组 3.3 数组和列表的区别是什么&#xff1f; 3.4 其它快速创建数组的方式 四、numpy爆破属性 五、numpy索引与切片 5.1 索引 5.2 切片 六、统计&聚合&矩阵操作 6.…

如何用VSCode和Clangd与Clang-Format插件高效阅读Linux内核源码及写驱动

一、如何高效阅读Linux源码&#xff1a;基于clangd uboot/busybox等都可以用这种方式&#xff0c;理论上说所有基于Make和Cmake的源码工程都可以用这套方案 阅读Linux源码最大问题在于调用链太复杂&#xff0c;一个函数或变量引用太多&#xff0c;source insight和cscope等基于…