{"id":28028642,"url":"https://github.com/abin-z/threadpool","last_synced_at":"2026-01-22T05:33:32.980Z","repository":{"id":289064223,"uuid":"969977985","full_name":"abin-z/ThreadPool","owner":"abin-z","description":"A cross-platform, header-only C++11 thread pool (线程池)","archived":false,"fork":false,"pushed_at":"2026-01-17T15:05:04.000Z","size":375,"stargazers_count":6,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-01-18T00:57:49.279Z","etag":null,"topics":["cpp","cpp11","mutilthread","task","task-manager","threadpool"],"latest_commit_sha":null,"homepage":"","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/abin-z.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,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-04-21T08:52:30.000Z","updated_at":"2026-01-17T15:05:07.000Z","dependencies_parsed_at":"2025-12-19T00:08:14.847Z","dependency_job_id":null,"html_url":"https://github.com/abin-z/ThreadPool","commit_stats":null,"previous_names":["abin-z/threadpool"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/abin-z/ThreadPool","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/abin-z%2FThreadPool","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/abin-z%2FThreadPool/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/abin-z%2FThreadPool/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/abin-z%2FThreadPool/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/abin-z","download_url":"https://codeload.github.com/abin-z/ThreadPool/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/abin-z%2FThreadPool/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28656289,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-22T01:17:37.254Z","status":"online","status_checked_at":"2026-01-22T02:00:07.137Z","response_time":144,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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","cpp11","mutilthread","task","task-manager","threadpool"],"created_at":"2025-05-11T07:20:34.849Z","updated_at":"2026-01-22T05:33:32.974Z","avatar_url":"https://github.com/abin-z.png","language":"C++","readme":"# Lightweight Thread Pool (C++11)\n\n[![threadpool](https://img.shields.io/badge/Thread_Pool-8A2BE2)](https://github.com/abin-z/ThreadPool) [![headeronly](https://img.shields.io/badge/Header_Only-green)](include/thread_pool/thread_pool.h) [![moderncpp](https://img.shields.io/badge/Modern_C%2B%2B-218c73)](https://learn.microsoft.com/en-us/cpp/cpp/welcome-back-to-cpp-modern-cpp?view=msvc-170) [![licenseMIT](https://img.shields.io/badge/License-MIT-green)](https://opensource.org/license/MIT) [![version](https://img.shields.io/badge/version-0.9.2-green)](https://github.com/abin-z/ThreadPool/releases)\n\n🌍 Languages/语言:  [English](README.md)  |  [简体中文](README.zh-CN.md)\n\n**A cross-platform, header-only, task-based C++11 thread pool supporting arbitrary arguments and return values via `std::future`.**\n\n## 📌 Overview\n\nA **Thread Pool** is a tool that manages threads based on the **pooling concept**, commonly used in multithreaded programming.\n\nThe core idea is: **a certain number of threads are pre-created and placed in a \"pool\". When a task arrives, it is assigned to an idle thread for processing, rather than creating a new thread every time.**\n\n![Thread_pool.svg](assets/Thread_pool.svg.png)\n\n## ✨ Features\n\n- **Flexible Task Submission**: Supports arbitrary callable types with arguments; returns a `std::future\u003cT\u003e`\n- **Thread-Safe**: Built using `std::mutex`, `std::condition_variable`, and `std::atomic`\n- **Cross-Platform**: Pure C++11 implementation, works on Windows, Linux, and more\n- **Header-Only**: Just include the single file `thread_pool.h` in your project\n- **RAII Resource Management**: Threads are cleanly shut down in destructor\n- **Task Completion Wait**: Supports waiting for all tasks to finish with `wait_all()`\n- **Shutdown Modes**:\n  - `WaitForAllTasks`: Complete all tasks before shutdown\n  - `DiscardPendingTasks`: Discard pending tasks and shut down immediately\n\n## 📦 Getting Started\n\n### Installation\n\nCopy [`thread_pool.h`](thread_pool/include/thread_pool/thread_pool.h) into your project and include it:\n\n```cpp\n#include \"thread_pool.h\"\n```\n\nNo additional dependencies required.\n\n### Basic Example\n\n**basic usage**\n\n```cpp\n#include \"thread_pool.h\"\n#include \u003ciostream\u003e\n\nint main() {\n  abin::threadpool pool(4);\n\n  auto future1 = pool.submit([] { return 42; });\n  std::cout \u003c\u003c \"Result: \" \u003c\u003c future1.get() \u003c\u003c \"\\n\";\n\n  auto future2 = pool.submit([](int a, int b) { return a + b; }, 5, 7);\n  std::cout \u003c\u003c \"Sum: \" \u003c\u003c future2.get() \u003c\u003c \"\\n\";\n\n  return 0;\n}\n```\n\n**Submit a callable object of any type with any arguments**\n\n\u003cdetails\u003e\n\u003csummary\u003eClick to expand and view the code\u003c/summary\u003e\n\n```cpp\n#include \"thread_pool.h\"\n\n#include \u003cfunctional\u003e\n#include \u003cfuture\u003e\n#include \u003ciostream\u003e\n#include \u003cstring\u003e\n\nvoid normal_function(int x)\n{\n  std::cout \u003c\u003c \"normal_function: \" \u003c\u003c x \u003c\u003c std::endl;\n}\n\nstruct MyClass\n{\n  void member_function(int y)\n  {\n    std::cout \u003c\u003c \"MyClass::member_function: \" \u003c\u003c y \u003c\u003c std::endl;\n  }\n  int add(int a, int b)\n  {\n    return a + b;\n  }\n};\n\nstruct Functor\n{\n  void operator()(const std::string\u0026 msg) const\n  {\n    std::cout \u003c\u003c \"Functor called with: \" \u003c\u003c msg \u003c\u003c std::endl;\n  }\n};\n\nint main()\n{\n  abin::threadpool pool(4);\n\n  // Submit a regular function\n  pool.submit(normal_function, 42);\n\n  // Submit a lambda without capture\n  pool.submit([] { std::cout \u003c\u003c \"lambda no capture\\n\"; });\n\n  // Submit a lambda with capture\n  int value = 99;\n  pool.submit([value] { std::cout \u003c\u003c \"lambda with capture: \" \u003c\u003c value \u003c\u003c \"\\n\"; });\n\n  // Submit a member function using lambda\n  MyClass obj;\n  pool.submit([\u0026obj] { obj.member_function(123); });\n\n  // Submit a member function using std::mem_fn\n  std::future\u003cint\u003e ret = pool.submit(std::mem_fn(\u0026MyClass::add), \u0026obj, 3, 4);\n  std::cout \u003c\u003c \"add result1: \" \u003c\u003c ret.get() \u003c\u003c \"\\n\";\n\n  // Submit a member function using std::bind\n  std::future\u003cint\u003e fut_add = pool.submit(std::bind(\u0026MyClass::add, \u0026obj, 2, 3));\n  std::cout \u003c\u003c \"add result2: \" \u003c\u003c fut_add.get() \u003c\u003c \"\\n\";\n\n  // Submit a function object (functor)\n  Functor f;\n  pool.submit(f, \"hello functor\");\n\n  // Submit using std::bind\n  auto bound = std::bind(\u0026MyClass::add, \u0026obj, 5, 6);\n  std::future\u003cint\u003e fut_bound = pool.submit(bound);\n  std::cout \u003c\u003c \"bound result: \" \u003c\u003c fut_bound.get() \u003c\u003c \"\\n\";\n\n  // Submit a std::packaged_task (Note: older versions of MSVC may report errors)\n  std::packaged_task\u003cstd::string()\u003e task([] { return std::string(\"from packaged_task\"); });\n  std::future\u003cstd::string\u003e fut_str = task.get_future();\n  pool.submit(std::move(task));  // Must be moved\n  std::cout \u003c\u003c \"packaged_task result: \" \u003c\u003c fut_str.get() \u003c\u003c \"\\n\";\n\n  pool.wait_all();  // Wait for all tasks to finish\n  std::cout \u003c\u003c \"===All tasks completed.===\\n\";\n}\n```\n\n\u003c/details\u003e\n\nFor more detailed use cases, please go to the [`examples`](examples/) folder to view them.\n\n## 📄 API Reference\n\n### Constructor \u0026 Destructor\n\n```cpp\nexplicit threadpool(std::size_t thread_count = default_thread_count());\n~threadpool();\n```\n\n- Initializes and launches the thread pool\n- Thread count defaults to `std::thread::hardware_concurrency()`, or 4 if unknown\n- Destructor automatically shuts down all threads (waits for tasks to complete)\n\n------\n\n### Task Submission\n\n```cpp\ntemplate \u003ctypename F, typename... Args\u003e\nauto submit(F\u0026\u0026 f, Args\u0026\u0026... args) -\u003e std::future\u003cdecltype(f(args...))\u003e;\n```\n\n- Asynchronously submits a task\n- Returns a `std::future\u003cT\u003e` for the result\n- Throws `std::runtime_error` if the pool is stopped\n\n------\n\n### Waiting for Completion\n\n```cpp\nvoid wait_all();\n```\n\n- Blocks until all tasks have finished\n- Returns immediately if no tasks are pending\n\n------\n\n### Shutdown\n\n```cpp\nvoid shutdown(shutdown_mode mode = shutdown_mode::WaitForAllTasks);\n```\n\n- Gracefully or forcefully stops the thread pool\n- Cannot submit new tasks after shutdown\n\n------\n\n### Restart\n\n```cpp\nvoid reboot(std::size_t thread_count);\n```\n\n- Shuts down current pool and restarts with new thread count\n- No effect if the pool is already running\n\n------\n\n### Status Queries\n\n```cpp\nbool is_running() const noexcept;                 // Whether the thread pool is running  \nstd::size_t total_threads() const noexcept;       // Total number of threads  \nstd::size_t busy_threads() const noexcept;        // Number of busy threads  \nstd::size_t idle_threads() const noexcept;        // Number of idle threads  \nstd::size_t pending_tasks() const noexcept;       // Number of pending tasks  \nthreadpool::status_info status() const noexcept;  // Summary of status info  \n```\n\n- Provides detailed insight into the internal state of the pool\n\n------\n\n## ✅ Recommended Scenarios for Using a Thread Pool\n\n| Scenario                                                     | Reason                                                       |\n| ------------------------------------------------------------ | ------------------------------------------------------------ |\n| Need to execute **a large number of small, independent tasks** | Avoid frequent thread creation/destruction, improve efficiency |\n| Tasks are short-lived                                        | Encourages thread reuse and fast response                    |\n| Tasks are **non-blocking**                                   | Prevents thread pool threads from being tied up              |\n| Want to control concurrency and save resources               | Limit thread count to avoid system overload                  |\n| Background asynchronous task handling                        | E.g., logging, delayed execution, event callbacks            |\n| Need unified thread lifecycle management                     | Easier centralized control, restarting, and destruction      |\n| Using `future`/`promise`-based mechanisms to retrieve results | Thread pool naturally fits task submission with result retrieval |\n\n## ⚠️ Scenarios Where a Thread Pool Is Not Recommended\n\n| Scenario                                                     | Reason                                                       |\n| ------------------------------------------------------------ | ------------------------------------------------------------ |\n| Need a **foreground thread**                                 | Thread pool threads are background by default, process can't rely on them to stay alive |\n| Need to **set thread priority**                              | Thread pool threads typically don't allow custom priority    |\n| **Tasks block for a long time** (e.g., I/O, locks)           | May exhaust the pool, blocking other tasks from starting     |\n| Need to place thread in a **single-threaded apartment (STA)** | Thread pool threads are usually in multi-threaded apartment (MTA) |\n| Need threads with **stable identity or persistent state**    | Thread pool threads are reused, not bound to specific context |\n| Need a thread **dedicated to a long-running task**           | Custom thread is more suitable for holding context and stability |\n\n## 💡 Contribution Guidelines\n\n🗨️ Welcome to submit **Issue** and **Pull request** to improve this project!\n\n-----\n\n## 🙌 Acknowledgements\n\nThanks to **[Catch2](https://github.com/catchorg/Catch2)** for providing great support and helping with unit testing of this project!\n\nThanks to **https://github.com/progschj/ThreadPool** for providing inspiration for this project!\n\n------\n\n## 📜 License\n\nThis project uses the [ **MIT** License](./LICENSE). \n\nCopyright © 2025–Present Abin.\n\n------\n\n## 🙋‍♂️ Author\n\n**Abin**  📎 [GitHub](https://github.com/abin-z)\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fabin-z%2Fthreadpool","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fabin-z%2Fthreadpool","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fabin-z%2Fthreadpool/lists"}