{"id":22076819,"url":"https://github.com/hengxin666/threadpool","last_synced_at":"2025-06-12T10:08:42.614Z","repository":{"id":219948870,"uuid":"750268036","full_name":"HengXin666/ThreadPool","owner":"HengXin666","description":"Linux,Windows轻量级C++线程池, 支持可变参数的函数/类方法/仿函数/匿名函数等等, 使用简单, 可自定义线程池增减规则, 日志打印等","archived":false,"fork":false,"pushed_at":"2024-09-05T07:37:03.000Z","size":882,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-23T20:21:56.237Z","etag":null,"topics":["cpp","threadpool"],"latest_commit_sha":null,"homepage":"","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/HengXin666.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-01-30T10:12:17.000Z","updated_at":"2024-09-05T07:37:06.000Z","dependencies_parsed_at":"2024-09-06T12:20:54.317Z","dependency_job_id":"552a7065-5a78-4cc4-8a7a-71bb94f95b59","html_url":"https://github.com/HengXin666/ThreadPool","commit_stats":null,"previous_names":["hengxin666/threadpool"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/HengXin666/ThreadPool","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HengXin666%2FThreadPool","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HengXin666%2FThreadPool/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HengXin666%2FThreadPool/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HengXin666%2FThreadPool/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/HengXin666","download_url":"https://codeload.github.com/HengXin666/ThreadPool/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HengXin666%2FThreadPool/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":259444946,"owners_count":22858547,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cpp","threadpool"],"created_at":"2024-11-30T22:28:23.485Z","updated_at":"2025-06-12T10:08:42.589Z","avatar_url":"https://github.com/HengXin666.png","language":"C++","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003ch1 align=\"center\"\u003eHXThreadPool\u003c/h1\u003e\nLinux, Windows 平台的轻量级C++线程池, 支持可变参数的函数/类方法/仿函数/匿名函数等等, 使用简单, 可自定义线程池增减规则, 日志打印等\n代码简单, 不过几百行.\n\u003cp align=\"center\"\u003e|\u003ca href=\"https://996.icu\"\u003e\u003cimg src=\"https://img.shields.io/badge/link-996.icu-red.svg\" alt=\"996.icu\"/\u003e\u003c/a\u003e|\u003ca href=\"https://github.com/HengXin666/ThreadPool\"\u003e\u003cimg alt=\"GitHub User's stars\" src=\"https://img.shields.io/github/stars/HengXin666%2FThreadPool?style=flat-square\u0026color=yellow\"\u003e\u003c/a\u003e|\u003ca href=\"https://github.com/HengXin666/ThreadPool\"\u003e\u003cimg src=\"https://img.shields.io/github/forks/HengXin666/ThreadPool?style=flat-square\u0026color=orange\" alt=\"GitHub forks\"/\u003e\u003c/a\u003e|\u003ca href=\"https://github.com/HengXin666/ThreadPool\"\u003e\u003cimg src=\"https://img.shields.io/github/watchers/HengXin666/ThreadPool?style=flat-square\u0026color=green\" alt=\"GitHub watchers\"/\u003e\u003c/a\u003e|\u003ca href=\"https://github.com/HengXin666\"\u003eHX\u003c/a\u003e|\n\u003c/p\u003e\n\n## 1. 安装\n\n### 1.1. 下载源码\n```shell\ngit clone https://github.com/HengXin666/ThreadPool.git\n```\n\n### 1.2. 找到需要的文件\n\n`code`目录下 \u003e\u003e `HXThreadPool.h` 和 `HXThreadPool.cpp`\n\n## 2. 使用\n### 2.1. 引入头文件\n```c++\n#include \u003ccstdio\u003e\n#include \"HXThreadPool.h\" // 我的线程池文件\n```\n\n### 2.2. 简单使用\n```c++\nint main() {\n    // 创建线程池\n\tHX::ThreadPool pool(2);\n\n    // 可以使用匿名函数/仿函数/函数, 并且参数数量/类型不限\n    pool.addTask([](int a, int b) { printf(\"hello world! %d + %d = %d\\n\", a, b, a + b); }, 1, 2);\n\n    return 0;\n}\n```\n\n使用示例图:\n\n![](./dev/appImg.png)\n\n本程序已经使用 `#include \"vld.h\"` 检测内存泄漏情况, 目前没有发现内存泄漏.\n\n### 2.3. Linux 编译\n\n(注:) **需要链接`pthread`库才可以使用!**\n\n```shell\ng++ -std=c++11 main.cpp HXThreadPool.cpp -l pthread -o app\n```\n\n## 3. 线程池类函数说明\n### 3.1. 线程池的创建\n\n简单的使用, 只需要指定`最小线程数`(`t_min`)即可 (`opTime`(检查 消费者线程 的时间间隔)或许也需要你的指定)\n\n```c++\n// 为什么需要核心数 - 1?, 因为 还有主线程 (-1); 还有一个管理者线程 (-1), 但是因为有时间间隔, 所以可以忽略...\n/**\n * @brief 创建线程池并初始化, [-1] 代表使用 (当前CPU的核心数 - 1)\n * @param t_min 最小线程数\n * @param t_max 最大线程数\n * @param taskMaxSize 最大任务数\n * @param opTime 管理者线程 检查 消费者线程 的时间间隔, 单位 ms\n */\nThreadPool(int t_min, int t_max = -1, int taskMaxSize = -1, int opTime = 2000);\n```\n\n### 3.2. 给线程池添加任务\n\n你可以添加任务, 任务可以是函数, 也可以是类方法, 也可以是仿函数, 也可以是lambda函数等等, 并且参数数量/类型不限\n\n- *如果您希望获得函数的返回值, 请使用引用或者指针作为参数传入*\n\n```c++\n/**\n * @brief 给线程池添加任务\n * @param func 子线程需要执行的任务可调用对象\n * @param ... 可调用对象分别对应的参数, 若没有可以为空 (只写参数func)\n * @return 添加成功 1, 出错 0\n */\ntemplate\u003ctypename Function, typename... Args\u003e\nbool addTask(Function\u0026\u0026 func, Args\u0026\u0026... args);\n\ntemplate\u003ctypename Function\u003e\nbool addTask(Function\u0026\u0026 func);\n```\n\n### 3.3. 查看线程池状态\n\n如下所示\n\n```c++\n/**\n * @brief 获取当前线程池忙碌的线程数\n * @param 无\n * @return 忙碌的线程数\n */\nint getPoolBusySize();\n\n/**\n * @brief 获取当前线程池存活的线程数\n * @param 无\n * @return 存活的线程数\n */\nint getPoolLiveSize();\n\n/**\n * @brief 获取当前线程池的任务队列的长度\n * @param 无\n * @return 任务队列的长度\n */\nint getTaskSize();\n```\n\n### 3.4. 关闭线程池\n\n您可以手动关闭, 也可以使用析构函数\n\n```c++\n// 销毁线程池\nvoid freeThreadPool();\n~ThreadPool();\n```\n\n## 4. 更多 自定义内容\n### 4.1. 指定线程池增减规则\n\n您可以指定线程池增减规则, 也可以不指定, 默认的规则是: \n\n- `任务的个数 \u003e 存活的线程个数 \u0026\u0026 存活的线程数 \u003c 最大线程数` 则**增加**线程\n\n- `忙的线程 * 2 \u003c 存活的线程数 \u0026\u0026 存活的线程 \u003e 最小线程数` 则**减少**线程\n\n只需要配置`函数指针`即可\n\n```c++\n/**\n * @brief 设置管理者线程判断函数\n * @param addPtr 单次增加的线程的判断函数\n * @param subPtr 单次减小的线程的判断函数\n * @return 无\n */\nvoid setSinglFunPtr(bool (*addPtr)(int, int, int, int, int, int, int) = ifAddThread ,\n                    bool (*subPtr)(int, int, int, int, int, int, int) = ifSubThread );\n```\n\n#### 函数指针参数介绍\n\n函数指针 执行 的函数, 其参数的顺序规定如下:\n\n- *注: 不论有没有使用, 在判断的时候均会进行下面参数的传参*\n\n示例:\n```c++\n/**\n * @brief 自带的增加线程数量 判断函数\n * @param now_taskSize 当前任务数\n * @param now_busy 当前繁忙的线程\n * @param now_idle 当前闲置的线程\n * @param now_live 当前存活的线程\n * @param t_min    线程池的最小线程数\n * @param t_max\t   线程池的最大线程数\n * @param taskMaxSize 任务队列最大长度\n * @return 0 不进行增加 / 1 进行增加\n */\nstatic bool ifAddThread(int now_taskSize, int now_busy, int now_idle, int now_live, int t_min, int t_max, int taskMaxSize);\n```\n\n### 4.2 设置线程池单次增减线程数量\n\n默认的线程池单次增减线程数量为 `SINGLE_NUME = 2`\n\n```c++\n/**\n * @brief 设置单次增减线程数量\n * @param add 单次增加的线程数量\n * @param sub 单次减小的线程数量\n * @return 无\n */\ninline void setSinglNumer(int add = SINGLE_NUME, int sub = SINGLE_NUME);\n```\n\n### 4.3 线程池类的成员\n```c++\n// --- 任务队列 组 ---\nstd::queue\u003cstd::function\u003cvoid()\u003e\u003e TP_threadTaskQueue;\t// 任务队列\nint taskMaxSize;\t\t\t\t\t// 任务数量\nint opTime;\t\t\t\t\t\t// 间隔检查时间\nstd::thread* TP_op;\t\t\t\t\t// 管理者线程\n\nstd::mutex TP_mutex_all;\t\t\t\t// 整个线程池的互斥锁\n\nstd::condition_variable taskQueueFull;\t\t// 条件变量: 任务队列满了\nstd::condition_variable taskQueueEmpty;\t\t// 条件变量: 任务队列空了\nstd::condition_variable freeConsumer_cond;\t// 条件变量: 需要释放的线程\n\nbool (*ifAddFunPtr)(int, int, int, int, int, int, int); // 函数指针指向是否增加线程的判断函数\nbool (*ifSubFunPtr)(int, int, int, int, int, int, int); // 函数指针指向是否减少线程的判断函数\n\n// --- 线程池 信息 ---\nint t_min;\t\t\t// 最小线程数\nint t_max;\t\t\t// 最大线程数\nint singleAdd;\t\t\t// 单次添加的线程数\nint singleSub;\t\t\t// 单次销毁的线程数\n\nstd::atomic_int TP_busy;         // 繁忙线程数 (正在执行任务)\nstd::atomic_int TP_idle;         // 空闲线程数 (已挂起)\nstd::atomic_int TP_live;         // 存活线程数 == 空闲线程数 + 繁忙线程数\nstd::atomic_int del_t_num;\t // 目前需要删除的线程数\n\n// --- 线程池 社畜 ---\nstd::map\u003cstd::thread::id, std::thread *\u003e TP_consumer;\t// 消费者红黑树 (添加/查找/删除 O(logN) 时间复杂度)\nstd::queue\u003cstd::thread*\u003e free_consumer;\t\t\t// 需要释放的线程\n\n// --- 线程池 开关 ---\nstd::atomic_bool TP_free;\t// 线程池是否释放\n```\n\n### 4.4 自定义日志函数\n\n\u003e [!TIP]\n\u003e 注: 这个和本项目[线程池]关系不大, 只不过我为了日后的方便顺手写的 qwq\n\n自定义单例输出类\n\n```c\nnamespace HX::tools {\n    // 单例-饿汉-输出类\n    class HXprint {\n        HXprint();\n    private:\n        HXprint(const HXprint\u0026) = delete;\n        HXprint\u0026 operator =(const HXprint\u0026) = delete;\n\n        // 自带输出正常\n        static void printInfo(const char* str, ...);\n\n        // 自带输出异常\n        static void printError(const char* str, ...);\n    public:\n        static HXprint* getHXprint();\n        \n        // 设置info输出函数\n        void setPrintInfoFun(void (*fun)(const char* str, ...));\n\n        // 设置error输出函数\n        void setPrintErrorFun(void (*fun)(const char* str, ...));\n        \n        void (*ptr_pInfo)(const char* str, ...);\n        void (*ptr_pError)(const char* str, ...);\n    };\n}\n```\n\n首先, 它是一个单例模型的类, 顾名思义, 整个程序中只有一个实例, 也就是全局的, 也就是你可以在任何地方调用`HX::tools::HXprint::getHXprint()`即可获取到全局的实例.\n\n其实现也非常简单:\n\n```c++\n// 构造函数\nHX::tools::HXprint::HXprint()\n{\n\tthis-\u003eptr_pInfo = printInfo;\n\tthis-\u003eptr_pError = printError;\n}\n\n// 获取实例\nHX::tools::HXprint* HX::tools::HXprint::getHXprint()\n{\n\tstatic HXprint hxPrint;\n\treturn \u0026hxPrint;\n}\n```\n\n关联到的函数指针, 其可以被替换, 以下是默认的函数指针:\n\n```c++\nvoid HX::tools::HXprint::printInfo(const char* str, ...)\n{\n\tva_list args;\n\tva_start(args, str);\n\n\t// 构建输出字符串\n\tchar buffer[CACHE_STR_ARR_SIZE_MAX];\n\tvsnprintf(buffer, sizeof(buffer), str, args);\n\n\tprintf(\"[INFO]: %s\\n\", buffer);\n\tva_end(args);\n}\n```\n\n使用它, 就如使用`printf()`一样:\n```c++\nauto print = HX::tools::HXprint::getHXprint();\nprint-\u003eptr_pInfo(\"我被使用啦%s~\", \"\u003ev\u003c\"); // 打印 \"[INFO]: 我被使用啦\u003ev\u003c~\\n\" 于控制台\n```\n\n如果你把它改为在日志函数中打印, 那么只需要:\n\n```c++\nvoid myPrint(const char* str, ...)\n{\n\tva_list args;\n\tva_start(args, str);\n    // -----------------------上面不能改\n\n\t// 构建输出字符串 (组装可变参数到字符串buffer中)\n\tchar buffer[CACHE_STR_ARR_SIZE_MAX];\n\tvsnprintf(buffer, sizeof(buffer), str, args);\n\n    // ------------------------上面最好不要改\n    // 随便你发挥\n\n\n    // 此处可以是你的日志函数 fprintf() 等等\n\tprintf(\"[DEBUG]: %s\\n\", buffer);\n\n    // -----------------------下面不能改\n\tva_end(args);\n}\n\nint main()\n{\n    // 绑定新的输出函数\n\tHX::tools::HXprint::getHXprint()-\u003esetPrintInfoFun(myPrint);\n    // ...\n}\n```\n\n## 5. 线程池原理与实现\n### 5.1 前置知识\n我们使用线程的时候就去创建一个线程，这样实现起来非常简便，但是就会有一个问题：如果并发的线程数量很多，并且每个线程都是执行一个时间很短的任务就结束了，这样频繁创建线程就会大大降低系统的效率，因为频繁创建线程和销毁线程需要时间。\n\n那么有没有一种办法使得**线程可以复用，就是执行完一个任务，并不被销毁，而是可以继续执行其他的任务**呢？\n\n线程池是一种多线程处理形式，处理过程中将任务添加到队列，然后在创建线程后自动启动这些任务。线程池线程都是后台线程。每个线程都使用默认的堆栈大小，以默认的优先级运行，并处于多线程单元中。如果某个线程在托管代码中空闲（如正在等待某个事件）,则线程池将插入另一个辅助线程来使所有处理器保持繁忙。如果所有线程池线程都始终保持繁忙，但队列中包含挂起的工作，则线程池将在一段时间后创建另一个辅助线程但线程的数目永远不会超过最大值。超过最大值的线程可以排队，但他们要等到其他线程完成后才启动。\n\n在各个编程语言的语种中都有线程池的概念，并且很多语言中直接提供了线程池，作为程序猿直接使用就可以了，下面给大家介绍一下线程池的实现原理：\n\n线程池的组成主要分为3个部分，这三部分配合工作就可以得到一个完整的线程池：\n\n- \u003cspan style=\"color:red\"\u003e任务队列，存储需要处理的任务，由工作的线程来处理这些任务\u003c/span\u003e\n\t- 通过线程池提供的API函数，将一个待处理的任务添加到任务队列，或者从任务队列中删除\n\t- 已处理的任务会被从任务队列中删除\n\t- 线程池的使用者，也就是调用线程池函数往任务队列中添加任务的线程就是生产者线程\n- \u003cspan style=\"color:red\"\u003e工作的线程（任务队列任务的消费者），N个\u003c/span\u003e\n\t- 线程池中维护了一定数量的工作线程, 他们的作用是是不停的读任务队列, 从里边取出任务并处理\n\t- 工作的线程相当于是任务队列的消费者角色，\n\t- 如果任务队列为空, 工作的线程将会被阻塞 (使用条件变量/信号量阻塞)\n\t- 如果阻塞之后有了新的任务, 由生产者将阻塞解除, 工作线程开始工作\n- \u003cspan style=\"color:red\"\u003e管理者线程（不处理任务队列中的任务），1个\u003c/span\u003e\n\t- 它的任务是周期性的对任务队列中的任务数量以及处于忙状态的工作线程个数进行检测\n\t- 当任务过多的时候, 可以适当的创建一些新的工作线程\n\t- 当任务过少的时候, 可以适当的销毁一些工作的线程\n\n![Clip_2024-01-20_21-29-14.png](./dev/tp.png)\n\n注意, 任务队列满了不一定是拒绝服务, 也有可能阻塞等待任务队列\n\n### 5.2 本项目的实现\n\n主要是一些感觉上是与众不同的点:\n\n- 消费者线程の销毁: 虽然线程会退出, 但是因为是 `std::thread *` 的类型, 所以还需要 `delete` 一下, 因此把它放进去 `std::queue\u003cstd::thread*\u003e free_consumer`里面, 并且在**管理者线程**把它销毁, 以防止内存泄漏.\n\n![](./dev/mainImg.png)\n\n其他的可以查看代码, 自认为我的注释还算可以的qwq...\n\n## 6. 小结\n这是我开发的轻量级C++线程池, 目的是为了巩固刚刚学习的`C++11`多线程编程(线程池/互斥锁/条件变量/原子操作等)\n\n我现在只是一名大一的学生(2024年1月30日), 代码可能写的很不好, 但希望你能理解. 如果出现了BUG, 希望您给我反馈, 这也是我的宝贵的学习机会!\n\n如果可以的话, 请给我一个star, 谢谢!\n\n## 7. 更新日志\n- 2024.01.30:\n    - 写好了这个东西...\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhengxin666%2Fthreadpool","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhengxin666%2Fthreadpool","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhengxin666%2Fthreadpool/lists"}