# simple-threadpool **Repository Path**: simple-set/simple-threadpool ## Basic Information - **Project Name**: simple-threadpool - **Description**: 轻量级C++线程池,API非常简洁,支持mac、windows、Linux等操作系统. - **Primary Language**: C++ - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-07-30 - **Last Updated**: 2024-08-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # simple-threadpool #### 介绍 轻量级C++线程池,API非常简洁,支持`mac`、`windows`、`Linux`等操作系统,部分特性 - 使用无界任务队列 - 支持核心线程和最大线程数,默认为cpu核心数相同, 可按需自行设置 - 支持无返回值任务、有返回支持任务,以及传递任意参数。 - 支持各种可执行对象,如:全局函数、类函数、仿函数、lambda表达式等(执行任务时,底层提交到任务队列,然后被工作线程获取并执行) #### 软件架构 使用C++标准库(STL)实现 #### 安装教程 项目使用cmake管理,可使用多种方式集成到项目, `add_subdirectory`、`find_package`、`FetchContent`等。 #### find_package 方式 - 安装到系统 ```shell $ git clone https://gitee.com/simple-set/simple-threadpool.git $ cd simple-threadpool && mkdir build && cd build $ cmake .. && cmake --build . $ cmake --install . --prefix=/opt/thread_pool # 注意安装路径 ``` - 在CMakeList.txt文件引入 ```cmake # 加载依赖 set(thread_pool_DIR /opt/thread_pool/share/cmake/) # 与安装路径匹配 find_package(thread_pool) # 链接依赖 add_executable(demo src/main.cpp) target_link_libraries(demo PRIVATE thread_pool) ``` #### FetchContent 方式 - 在CMakeList.txt文件引入即可 ``` cmake # 加载依赖 include(FetchContent) FetchContent_Declare( thread_pool GIT_REPOSITORY https://gitee.com/simple-set/simple-threadpool.git GIT_TAG v1.0.0 ) FetchContent_MakeAvailable(thread_pool) # 链接依赖 add_executable(demo src/main.cpp) target_link_libraries(demo PRIVATE thread_pool) ``` #### 使用说明 异步执行任务,支持各种可执行对象,如:全局函数、类函数、仿函数、lambda表达式等。执行任务时,底层提交到任务队列,然后等待工作线程获取并执行。 - 普通任务 ```c++ #include #include "thread_pool.h" void runable() { std::cout << "hello world" << std::endl; } int main(int argc, char **argv) { simpleThread::ThreadPool pool; pool.execute(runable); pool.join(); return 0; } ``` - 返回值任务 ```c++ #include #include "thread_pool.h" int getValue(int i) { return 10; } int main(int argc, char **argv) { auto res = pool.submit(getValue, 10); std::cout << res.get() << std::endl; pool.join(); return 0; } ``` API列表 - `simpleThread::ThreadPool poo` 默认构造函数, 核心线程数和最大线程数,与cpu核心数相同 - `simpleThread::ThreadPool poo(4, 10)` 指定核心线程4, 最大线程数10 - `pool.execute(F &&f, Args &&... args)` 异步执行普通任务,支持传参 - `pool.submit(F &&f, Args &&... args)` 异步执行有返回值的任务,支持参数 - `pool.join()` 阻塞调用,等所有任务完成,然后关闭线程池 - `pool.shutdown()` 阻塞调用,正在执行的任务继续完成,队列中等待执行的任务丢弃,然后关闭线程池。 #### 参与贡献 1. Fork 本仓库 2. 新建 Feat_xxx 分支 3. 提交代码 4. 新建 Pull Request