# ThreadPool **Repository Path**: outer-circle-inner-gk/thread-pool ## Basic Information - **Project Name**: ThreadPool - **Description**: 使用C++11实现的平台无关的线程池 - **Primary Language**: Unknown - **License**: WTFPL - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 3 - **Created**: 2022-09-20 - **Last Updated**: 2022-09-20 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 线程池项目说明 ## 目录结构 ``` thread-pool |-- CMakeLists.txt # cmake工程管理文件 |-- example.cpp # 测试demo |-- threadpool |-- CMakeLists.txt # cmake工程管理文件 |-- Task.hpp # 线程池中允许的任务的抽象基类 |-- TaskQueue.hpp # 任务队列的实现 |-- ThreadPool.hpp/cpp # 线程池的实现 |-- ThreadUtils.hpp # 线程工具函数,提取线程ID |-- WorkThread.hpp/cpp # 工作线程 ``` ## 使用 参照example.cpp代码 ```cpp #include #include "ThreadPool.hpp" // 定义字节的任务类,继承Task基类 class MyTask : public Task { public: MyTask(int i) : Task("MyTask" + std::to_string(i)) {} // 实现Task类的Run函数,最终线程池里会调用该函数 void Run() { for (int i = 0; i < 5; i++) { printf("-- thread [%3d]: task_name=[%20s], out=%d\n", GetThreadId(), GetName().c_str(), i); std::this_thread::sleep_for(std::chrono::seconds(1)); } } }; int main(int argc, char **argv) { ThreadPool pool; for (int i = 0; i < 50; i++) { pool.AddTask(std::make_shared(i)); } int i = 100; while(i < 150) { pool.AddTask(std::make_shared(i)); std::this_thread::sleep_for(std::chrono::seconds(1)); i++; } pool.Finish(); // 记得终止线程池 return 0; } ```