# C++简易版线程池 **Repository Path**: luckkeyhub/c_plus_plus-simplified-thread-pool ## Basic Information - **Project Name**: C++简易版线程池 - **Description**: 用C++实现的简易线程池. - **Primary Language**: C++ - **License**: AGPL-3.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 2 - **Forks**: 0 - **Created**: 2024-02-08 - **Last Updated**: 2025-02-28 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # C++简易版线程池 #### 介绍 用C++实现的简易线程池.目前实现了两个版本. #### 目录结构 thread_pool 线程池版本1 - include - task.h 定义了任务抽象类 - taskQueue.hpp 任务队列. - thread_pool.h 线程池头文件 - src - thread_pool.cpp 线程池实现 - example.cpp 使用例子 - CMakeLists.txt 版本为2.8.12 Windows Linux下通用. thread_pool2 线程池版本2 - include - taskQueue.hpp 任务队列. - thread_pool.h 线程池头文件 - src - thread_pool.cpp 线程池实现 - example.cpp 使用例子 - CMakeLists.txt 版本为2.8.12 Windows Linux下通用. #### 编译案例 如果你想编译案例,你可以在build目录下使用cmake .. , 然后make一下, 生成的可执行文件在bin目录中. ### thread_pool(线程池版本1)的一些说明: **每个任务都要继承 lakes::TaskAbstract 实现 void Task();** ``` class Task1 : public lakes::TaskAbstract { public: Task1(int num) { _num = num; } ~Task1() { } void Task() override { printf("%d : %d\n", std::this_thread::get_id(), _num); std::chrono::seconds dura(1); std::this_thread::sleep_for(dura); } private: int _num; }; ``` **可设置钩子函数监视线程池状况, 第一个参数是间隔时间, 单位为毫秒.** ``` pool.setHook(1000, [](lakes::ThreadPool* pool) { printf("now statubusyThread: %d liveThread: %d queueNum : %d\n", pool->getBusyThreadNumber(), pool->getLiveThreadNumber(), pool->getTaskQueueNumber()); }); ``` **使用案例** ``` int main() { lakes::ThreadPool pool(2, 7); /* 或者 lakes::ThreadPool pool(2, 7, false); // ... pool.start(); 在创建时就不会启用线程池. */ pool.setHook(1000, [](lakes::ThreadPool* pool) { printf("now statubusyThread: %d liveThread: %d queueNum : %d\n", pool->getBusyThreadNumber(), pool->getLiveThreadNumber(), pool->getTaskQueueNumber()); }); for (int i = 0; i < 100; i++) { pool.addTask(new Task1(i)); } std::this_thread::sleep_for(std::chrono::seconds(30)); pool.finish(); // 手动停止, 也可以不调用, 析构函数会自动调用. return 0; } ``` **不知道有没有用的函数.** ``` 在lakes::TaskAbstract 有一个getThreadPool() 可以获得当前线程所处的线程池对象, 你可以在你的任务中查看线程池状况, 或添加新的任务. ``` ### thread_pool2(线程池版本2)的一些说明: **大部分和版本1相同, 主要讲不一样的地方.** 注意: _1. 版本2没有了 lakes::TaskAbstract类, 你不需要像之前那样继承lakes::TaskAbstract在实现相应任务._ _2. addTask()变成了commit更加灵活._ **commit 普通函数** ``` void say(int i) { printf("say__tid:%ld, %d\n", std::this_thread::get_id(), i); std::this_thread::sleep_for(std::chrono::seconds(1)); } int main() { //... for (int i = 0; i < 100; i++) { pool.commit(say, i); } //... } ``` **commit Lambda表达式** ``` for (int i = 0; i < 100; i++) { pool.commit([](int i) { printf("Lambda__tid:%ld, %d\n", std::this_thread::get_id(), i); std::this_thread::sleep_for(std::chrono::seconds(1)); }, i); } ``` **获取任务返回值** ``` int add(int a, int b) { return a + b; } int main() { // 获取函数返回值 std::futureval = pool.commit(add, 3, 5); // ... // 在未来某个节点. printf("a + b = %d\n", val.get()); } ```