{"id":29538769,"url":"https://github.com/hsll175848494/lfthreadpool","last_synced_at":"2025-07-17T05:16:00.528Z","repository":{"id":304558633,"uuid":"1019138888","full_name":"HSLL175848494/LFThreadPool","owner":"HSLL175848494","description":"基于栈分配任务容器的 C++11 仅头文件线程池 | A header-only C++11 thread pool based on stack-allocated task containers","archived":false,"fork":false,"pushed_at":"2025-07-13T20:46:33.000Z","size":75,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-07-13T22:23:30.472Z","etag":null,"topics":["cpp","header-only","load-balance","muti-platform","threadpool"],"latest_commit_sha":null,"homepage":"","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/HSLL175848494.png","metadata":{"files":{"readme":"README.en.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,"zenodo":null}},"created_at":"2025-07-13T20:27:40.000Z","updated_at":"2025-07-13T20:46:36.000Z","dependencies_parsed_at":"2025-07-13T22:23:31.501Z","dependency_job_id":"005ddf7a-2fb7-4a26-b8a4-a20973669c76","html_url":"https://github.com/HSLL175848494/LFThreadPool","commit_stats":null,"previous_names":["hsll175848494/lfthreadpool"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/HSLL175848494/LFThreadPool","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HSLL175848494%2FLFThreadPool","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HSLL175848494%2FLFThreadPool/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HSLL175848494%2FLFThreadPool/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HSLL175848494%2FLFThreadPool/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/HSLL175848494","download_url":"https://codeload.github.com/HSLL175848494/LFThreadPool/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HSLL175848494%2FLFThreadPool/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":265567448,"owners_count":23789483,"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","header-only","load-balance","muti-platform","threadpool"],"created_at":"2025-07-17T05:15:34.428Z","updated_at":"2025-07-17T05:16:00.511Z","avatar_url":"https://github.com/HSLL175848494.png","language":"C++","funding_links":[],"categories":[],"sub_categories":[],"readme":"# HSLL::LFThreadPool\r\n\r\n## Overview\r\n\r\nThis is a lightweight C++11 thread pool implementation that **requires only header files** to use.\r\n\r\nIts core advantages lie in **efficiency and flexibility**:\r\n*   **Avoids dynamic memory allocation:** Uses stack-based pre-allocated task containers to store tasks and their parameters directly on the stack.\r\n*   **Multiple submission methods:** Supports submitting single tasks or batches of tasks to meet different scenario requirements.\r\n*   **Intelligent load balancing:** Combines Round-Robin scheduling, secondary queue selection, and work-stealing mechanisms to effectively distribute workload.\r\n*   **Resource optimization:** Dynamically adjusts the number of active threads based on current load, reducing unnecessary memory usage.\r\n*   **Graceful shutdown:** Provides two shutdown modes: immediate shutdown or waiting for all tasks to complete before shutting down.\r\n\r\n## Integration\r\n```cpp\r\n// Ensure the 'basic' folder is in the same directory\r\n#include \"ThreadPool.hpp\"\r\n```\r\n\r\n## ThreadPool Class Template\r\n\r\n### Template Parameters\r\n```cpp\r\ntemplate \u003cclass TYPE = TaskStack\u003c\u003e\u003e\r\nclass ThreadPool\r\n```\r\n- `TYPE`: Stack-based pre-allocated task container (see TaskStack.md documentation for details)\r\n\r\n### Initialization Method\r\n```cpp\r\nbool init(unsigned int queueLength, unsigned int minThreadNum,\r\n            unsigned int maxThreadNum, unsigned int batchSize = 1,\r\n            std::chrono::milliseconds adjustInterval = std::chrono::milliseconds(3000))\r\n```\r\n- **Parameters**:\r\n  - `queueLength`: Capacity of each work queue\r\n  - `minThreadNum`: Minimum number of worker threads\r\n  - `maxThreadNum`: Maximum number of worker threads\r\n  - `batchSize`: Number of tasks processed in a single batch\r\n  - `adjustInterval`: Interval for dynamic adjustment of active thread count\r\n- **Return value**: Returns true if initialization is successful\r\n- **Function**: Allocates resources and starts worker threads (initial count equals maxThreadNum)\r\n\r\n### Shutdown Method\r\n```cpp\r\nvoid exit(bool shutdownPolicy = true)\r\n```\r\n- `shutdownPolicy`: \r\n  - true: Graceful shutdown (executes remaining tasks in the queue)\r\n  - false: Immediate shutdown\r\n\r\n## Task Submission Interfaces\r\n\r\n| Method Type      | Interface     |\r\n|-------------|------------|\r\n| Single task submission    | emplace    | \r\n| Pre-constructed task   | enqueue     | \r\n| Bulk tasks     | enqueue_bulk| \r\n\r\n## Basic Usage\r\n```cpp\r\n#include \"ThreadPool.hpp\"\r\n\r\nusing namespace HSLL;\r\nusing Type = TaskStack\u003c64,8\u003e; // Task container with max size 64 bytes, max alignment 8\r\n\r\nvoid Func(int a, double b) { /*...*/ }\r\n\r\nint main()\r\n{\r\n    // Create thread pool instance with task container type Type\r\n    ThreadPool\u003cType\u003e pool;\r\n\r\n    // Initialize thread pool: queue capacity 1000, min threads 1, max threads 4\r\n    pool.init(1000, 1, 4); \r\n\r\n    // Add task - basic example\r\n    Type task(Func, 42, 3.14);\r\n    pool.enqueue(task);\r\n\r\n    // Add task - in-place construction\r\n    pool.emplace(Func, 42, 3.14); // Avoids temporary object construction vs enqueue\r\n\r\n    // Add task - std::function\r\n    std::function\u003cvoid(int,int)\u003e func(Func);\r\n    pool.emplace(f,42,3.14);\r\n\r\n    // Add task - lambda\r\n    pool.enqueue([](int a,int b){});\r\n\r\n    // exit(false) is automatically called on pool destruction, \r\n    // but manual call is recommended to control shutdown behavior\r\n    pool.exit(true); // Graceful shutdown. Can reinitialize via init() later\r\n\r\n    return 0;\r\n}\r\n```\r\n**See example files for additional usage patterns**\r\n\r\n## Task Lifecycle\r\n```mermaid\r\ngraph TD\r\n    A[Task Submission] --\u003e B{Submission Method}\r\n    B --\u003e|emplace| C[Construct task directly in queue]\r\n    B --\u003e|enqueue/enqueue_bulk| D[Copy/Move pre-constructed task into queue]\r\n    \r\n    C --\u003e E[Retrieve task via move]\r\n    D --\u003e E\r\n    \r\n    E --\u003e F[Execute task]\r\n    F --\u003e G[Explicitly call destructor]\r\n    G --\u003e H[Clean up execution memory]\r\n```\r\n\r\n## Parameter Passing Process\r\n```mermaid\r\ngraph LR\r\n    A[Construct Task] --\u003e B[Parameter Passing]\r\n    B --\u003e C{Lvalue Parameter}\r\n    B --\u003e D{Rvalue Parameter}\r\n    C --\u003e E[Copy to task container]\r\n    D --\u003e F[Move to task container]\r\n    \r\n    H[Execute Task]  --\u003e I[Parameters passed as lvalue references]\r\n    E --\u003e H\r\n    F --\u003e H\r\n    \r\n    I --\u003e J[Function Call]\r\n    J --\u003e K{Parameter Type}\r\n    K --\u003e L[By-value T]\r\n    K --\u003e M[Lvalue reference T\u0026]\r\n    K --\u003e N[Const reference const T\u0026]\r\n    K --\u003e O[Unsupported: Rvalue reference T\u0026\u0026 ]:::unsupported\r\n    \r\n    classDef unsupported fill:#f10,stroke:#333\r\n```\r\n\r\n## Important Notes\r\n1. **Type Matching**: Submitted task types MUST exactly match the queue's task type\r\n2. **Alignment Requirements**: Task max alignment MUST be ≤ queue task type's alignment\r\n3. **Exception Safety**:\r\n   - NO exceptions allowed during enqueue operations\r\n   - `emplace` interfaces require task (parameter/copy/move) constructions to be noexcept\r\n   - Other interfaces require task (copy/move) constructions to be noexcept\r\n   - `execute()` MUST NOT throw - catch and handle all possible exceptions within tasks\r\n     \r\n**Unlike heap-allocated tasks, copying stack-allocated tasks can fail. Since exceptions from asynchronously executed stack tasks cannot propagate to the caller, strict exception guarantees are a necessary compromise for stack-based task storage.**\r\n\r\n## Platform Support\r\n- Linux (aligned_alloc)\r\n- Windows (aligned_malloc)\r\n- C++11 or newer standard\r\n\r\n## Project Structure\r\n\r\n- 📂 document--------------------Documentation\r\n- 📂 example---------------------Usage examples\r\n- 📂 include---------------------Include directory\r\n- 📂 perf_test-------------------Performance tests\r\n- 📂 single_header_version-------Single-header version\r\n- 📄 README.md-------------------Chinese project documentation\r\n- 📄 README.en.md----------------English project documentation\r\n\r\nHere is the translation:\r\n\r\n## Other\r\n\r\nThis is a version where the current queue has been replaced with `moodycamel::ConcurrentQueue`, demonstrating significantly improved performance:  \r\n[LFThreadPool2](https://github.com/HSLL175848494/LFThreadPool2)","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhsll175848494%2Flfthreadpool","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhsll175848494%2Flfthreadpool","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhsll175848494%2Flfthreadpool/lists"}