{"id":2101,"date":"2024-07-10T20:32:00","date_gmt":"2024-07-10T20:32:00","guid":{"rendered":"https:\/\/www.w3computing.com\/articles\/?p=2101"},"modified":"2024-07-10T20:35:41","modified_gmt":"2024-07-10T20:35:41","slug":"how-to-create-a-custom-thread-pool-in-cpp","status":"publish","type":"post","link":"https:\/\/www.w3computing.com\/articles\/how-to-create-a-custom-thread-pool-in-cpp\/","title":{"rendered":"How to Create a Custom Thread Pool in C++"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Creating a custom thread pool in C++ is an essential skill for developers who need to manage multiple threads efficiently. This tutorial will guide you through the process of designing and implementing a thread pool from scratch. By the end, you will have a solid understanding of thread management and how to optimize concurrent tasks in C++.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">1. Introduction to Thread Pools<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What is a Thread Pool?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A thread pool is a collection of pre-initialized threads that stand by to perform tasks. Instead of creating and destroying threads for each task, which can be costly, a thread pool reuses a fixed number of threads. This approach improves performance and resource management, especially in applications requiring high concurrency.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why Use a Thread Pool?<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Efficiency<\/strong>: Reusing threads reduces the overhead associated with thread creation and destruction.<\/li>\n\n\n\n<li><strong>Resource Management<\/strong>: Limiting the number of threads prevents resource exhaustion.<\/li>\n\n\n\n<li><strong>Scalability<\/strong>: Thread pools help manage load by controlling the number of active threads.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">2. Setting Up the Development Environment<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Before we start, ensure you have a modern C++ compiler (C++11 or later) and a suitable development environment.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Required Tools<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Compiler<\/strong>: GCC, Clang, or MSVC supporting C++11 or later.<\/li>\n\n\n\n<li><strong>IDE<\/strong>: Visual Studio, CLion, or any preferred text editor.<\/li>\n\n\n\n<li><strong>Build System<\/strong>: CMake or Makefile.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Setting Up a Project<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a new C++ project in your preferred IDE. For this tutorial, we&#8217;ll use CMake to manage our build process. Create a <code>CMakeLists.txt<\/code> file:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"CMake\" data-shcb-language-slug=\"cmake\"><span><code class=\"hljs language-cmake\"><span class=\"hljs-keyword\">cmake_minimum_required<\/span>(VERSION <span class=\"hljs-number\">3.10<\/span>)\n<span class=\"hljs-keyword\">project<\/span>(ThreadPoolExample)\n\n<span class=\"hljs-keyword\">set<\/span>(CMAKE_CXX_STANDARD <span class=\"hljs-number\">11<\/span>)\n\n<span class=\"hljs-keyword\">add_executable<\/span>(ThreadPoolExample main.cpp)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">CMake<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cmake<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">3. Designing the Thread Pool<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Basic Design<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A thread pool typically consists of:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Worker Threads<\/strong>: A fixed number of threads that execute tasks.<\/li>\n\n\n\n<li><strong>Task Queue<\/strong>: A thread-safe queue to hold tasks waiting to be executed.<\/li>\n\n\n\n<li><strong>Task<\/strong>: A unit of work that can be processed by the worker threads.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Core Components<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>ThreadPool Class<\/strong>: Manages the lifecycle of worker threads and task queue.<\/li>\n\n\n\n<li><strong>Task Queue<\/strong>: A thread-safe queue to store tasks.<\/li>\n\n\n\n<li><strong>Worker Thread<\/strong>: A thread that continuously fetches and executes tasks from the queue.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Class Structure<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">We&#8217;ll define a basic class structure for our thread pool:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"C++\" data-shcb-language-slug=\"cpp\"><span><code class=\"hljs language-cpp\"><span class=\"hljs-meta\">#<span class=\"hljs-meta-keyword\">include<\/span> <span class=\"hljs-meta-string\">&lt;vector&gt;<\/span><\/span>\n<span class=\"hljs-meta\">#<span class=\"hljs-meta-keyword\">include<\/span> <span class=\"hljs-meta-string\">&lt;queue&gt;<\/span><\/span>\n<span class=\"hljs-meta\">#<span class=\"hljs-meta-keyword\">include<\/span> <span class=\"hljs-meta-string\">&lt;thread&gt;<\/span><\/span>\n<span class=\"hljs-meta\">#<span class=\"hljs-meta-keyword\">include<\/span> <span class=\"hljs-meta-string\">&lt;mutex&gt;<\/span><\/span>\n<span class=\"hljs-meta\">#<span class=\"hljs-meta-keyword\">include<\/span> <span class=\"hljs-meta-string\">&lt;condition_variable&gt;<\/span><\/span>\n<span class=\"hljs-meta\">#<span class=\"hljs-meta-keyword\">include<\/span> <span class=\"hljs-meta-string\">&lt;functional&gt;<\/span><\/span>\n<span class=\"hljs-meta\">#<span class=\"hljs-meta-keyword\">include<\/span> <span class=\"hljs-meta-string\">&lt;future&gt;<\/span><\/span>\n\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">ThreadPool<\/span> {<\/span>\n<span class=\"hljs-keyword\">public<\/span>:\n    ThreadPool(<span class=\"hljs-keyword\">size_t<\/span> threads);\n    ~ThreadPool();\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">template<\/span>&lt;class F, class... Args&gt;\n    <span class=\"hljs-keyword\">auto<\/span> <span class=\"hljs-title\">enqueue<\/span><span class=\"hljs-params\">(F&amp;&amp; f, Args&amp;&amp;... args)<\/span> -&gt; <span class=\"hljs-built_in\">std<\/span>::<span class=\"hljs-built_in\">future<\/span>&lt;<span class=\"hljs-keyword\">typename<\/span> <span class=\"hljs-built_in\">std<\/span>::result_of&lt;<span class=\"hljs-title\">F<\/span><span class=\"hljs-params\">(Args...)<\/span>&gt;::type&gt;<\/span>;\n\n<span class=\"hljs-keyword\">private<\/span>:\n    <span class=\"hljs-comment\">\/\/ Worker threads<\/span>\n    <span class=\"hljs-built_in\">std<\/span>::<span class=\"hljs-built_in\">vector<\/span>&lt;<span class=\"hljs-built_in\">std<\/span>::thread&gt; workers;\n    <span class=\"hljs-comment\">\/\/ Task queue<\/span>\n    <span class=\"hljs-built_in\">std<\/span>::<span class=\"hljs-built_in\">queue<\/span>&lt;<span class=\"hljs-built_in\">std<\/span>::function&lt;<span class=\"hljs-keyword\">void<\/span>()&gt;&gt; tasks;\n\n    <span class=\"hljs-comment\">\/\/ Synchronization<\/span>\n    <span class=\"hljs-built_in\">std<\/span>::mutex queue_mutex;\n    <span class=\"hljs-built_in\">std<\/span>::condition_variable condition;\n    <span class=\"hljs-keyword\">bool<\/span> stop;\n};<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C++<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cpp<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">4. Implementing the Thread Pool<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Constructor and Destructor<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In the constructor, we initialize the worker threads. The destructor ensures proper cleanup.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"C++\" data-shcb-language-slug=\"cpp\"><span><code class=\"hljs language-cpp\">ThreadPool::ThreadPool(<span class=\"hljs-keyword\">size_t<\/span> threads) : stop(<span class=\"hljs-literal\">false<\/span>) {\n    <span class=\"hljs-keyword\">for<\/span> (<span class=\"hljs-keyword\">size_t<\/span> i = <span class=\"hljs-number\">0<\/span>; i &lt; threads; ++i) {\n        workers.emplace_back(&#91;<span class=\"hljs-keyword\">this<\/span>] {\n            <span class=\"hljs-keyword\">while<\/span> (<span class=\"hljs-literal\">true<\/span>) {\n                <span class=\"hljs-built_in\">std<\/span>::function&lt;<span class=\"hljs-keyword\">void<\/span>()&gt; task;\n\n                {\n                    <span class=\"hljs-built_in\">std<\/span>::unique_lock&lt;<span class=\"hljs-built_in\">std<\/span>::mutex&gt; lock(<span class=\"hljs-keyword\">this<\/span>-&gt;queue_mutex);\n                    <span class=\"hljs-keyword\">this<\/span>-&gt;condition.wait(lock, &#91;<span class=\"hljs-keyword\">this<\/span>] {\n                        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">this<\/span>-&gt;stop || !<span class=\"hljs-keyword\">this<\/span>-&gt;tasks.empty();\n                    });\n\n                    <span class=\"hljs-keyword\">if<\/span> (<span class=\"hljs-keyword\">this<\/span>-&gt;stop &amp;&amp; <span class=\"hljs-keyword\">this<\/span>-&gt;tasks.empty())\n                        <span class=\"hljs-keyword\">return<\/span>;\n\n                    task = <span class=\"hljs-built_in\">std<\/span>::move(<span class=\"hljs-keyword\">this<\/span>-&gt;tasks.front());\n                    <span class=\"hljs-keyword\">this<\/span>-&gt;tasks.pop();\n                }\n\n                task();\n            }\n        });\n    }\n}\n\nThreadPool::~ThreadPool() {\n    {\n        <span class=\"hljs-function\"><span class=\"hljs-built_in\">std<\/span>::unique_lock&lt;<span class=\"hljs-built_in\">std<\/span>::mutex&gt; <span class=\"hljs-title\">lock<\/span><span class=\"hljs-params\">(queue_mutex)<\/span><\/span>;\n        stop = <span class=\"hljs-literal\">true<\/span>;\n    }\n\n    condition.notify_all();\n    <span class=\"hljs-keyword\">for<\/span> (<span class=\"hljs-built_in\">std<\/span>::thread &amp;worker : workers)\n        worker.join();\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C++<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cpp<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\">Adding Task Management<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>enqueue<\/code> method allows adding tasks to the task queue. It returns a <code>std::future<\/code> that can be used to retrieve the result of the task.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"C++\" data-shcb-language-slug=\"cpp\"><span><code class=\"hljs language-cpp\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">template<\/span>&lt;class F, class... Args&gt;\n<span class=\"hljs-keyword\">auto<\/span> <span class=\"hljs-title\">ThreadPool::enqueue<\/span><span class=\"hljs-params\">(F&amp;&amp; f, Args&amp;&amp;... args)<\/span> -&gt; <span class=\"hljs-built_in\">std<\/span>::<span class=\"hljs-built_in\">future<\/span>&lt;<span class=\"hljs-keyword\">typename<\/span> <span class=\"hljs-built_in\">std<\/span>::result_of&lt;<span class=\"hljs-title\">F<\/span><span class=\"hljs-params\">(Args...)<\/span>&gt;::type&gt; <\/span>{\n    <span class=\"hljs-keyword\">using<\/span> return_type = <span class=\"hljs-keyword\">typename<\/span> <span class=\"hljs-built_in\">std<\/span>::result_of&lt;F(Args...)&gt;::type;\n\n    <span class=\"hljs-keyword\">auto<\/span> task = <span class=\"hljs-built_in\">std<\/span>::make_shared&lt;<span class=\"hljs-built_in\">std<\/span>::packaged_task&lt;return_type()&gt;&gt;(\n        <span class=\"hljs-built_in\">std<\/span>::bind(<span class=\"hljs-built_in\">std<\/span>::forward&lt;F&gt;(f), <span class=\"hljs-built_in\">std<\/span>::forward&lt;Args&gt;(args)...)\n    );\n\n    <span class=\"hljs-built_in\">std<\/span>::<span class=\"hljs-built_in\">future<\/span>&lt;return_type&gt; res = task-&gt;get_future();\n    {\n        <span class=\"hljs-function\"><span class=\"hljs-built_in\">std<\/span>::unique_lock&lt;<span class=\"hljs-built_in\">std<\/span>::mutex&gt; <span class=\"hljs-title\">lock<\/span><span class=\"hljs-params\">(queue_mutex)<\/span><\/span>;\n\n        <span class=\"hljs-keyword\">if<\/span> (stop)\n            <span class=\"hljs-keyword\">throw<\/span> <span class=\"hljs-built_in\">std<\/span>::runtime_error(<span class=\"hljs-string\">\"enqueue on stopped ThreadPool\"<\/span>);\n\n        tasks.emplace(&#91;task]() { (*task)(); });\n    }\n\n    condition.notify_one();\n    <span class=\"hljs-keyword\">return<\/span> res;\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C++<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cpp<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">5. Adding Task Management<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Enqueue Method<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>enqueue<\/code> method allows adding tasks to the task queue. It returns a <code>std::future<\/code> that can be used to retrieve the result of the task.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"C++\" data-shcb-language-slug=\"cpp\"><span><code class=\"hljs language-cpp\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">template<\/span>&lt;class F, class... Args&gt;\n<span class=\"hljs-keyword\">auto<\/span> <span class=\"hljs-title\">ThreadPool::enqueue<\/span><span class=\"hljs-params\">(F&amp;&amp; f, Args&amp;&amp;... args)<\/span> -&gt; <span class=\"hljs-built_in\">std<\/span>::<span class=\"hljs-built_in\">future<\/span>&lt;<span class=\"hljs-keyword\">typename<\/span> <span class=\"hljs-built_in\">std<\/span>::result_of&lt;<span class=\"hljs-title\">F<\/span><span class=\"hljs-params\">(Args...)<\/span>&gt;::type&gt; <\/span>{\n    <span class=\"hljs-keyword\">using<\/span> return_type = <span class=\"hljs-keyword\">typename<\/span> <span class=\"hljs-built_in\">std<\/span>::result_of&lt;F(Args...)&gt;::type;\n\n    <span class=\"hljs-keyword\">auto<\/span> task = <span class=\"hljs-built_in\">std<\/span>::make_shared&lt;<span class=\"hljs-built_in\">std<\/span>::packaged_task&lt;return_type()&gt;&gt;(\n        <span class=\"hljs-built_in\">std<\/span>::bind(<span class=\"hljs-built_in\">std<\/span>::forward&lt;F&gt;(f), <span class=\"hljs-built_in\">std<\/span>::forward&lt;Args&gt;(args)...)\n    );\n\n    <span class=\"hljs-built_in\">std<\/span>::<span class=\"hljs-built_in\">future<\/span>&lt;return_type&gt; res = task-&gt;get_future();\n    {\n        <span class=\"hljs-function\"><span class=\"hljs-built_in\">std<\/span>::unique_lock&lt;<span class=\"hljs-built_in\">std<\/span>::mutex&gt; <span class=\"hljs-title\">lock<\/span><span class=\"hljs-params\">(queue_mutex)<\/span><\/span>;\n\n        <span class=\"hljs-keyword\">if<\/span> (stop)\n            <span class=\"hljs-keyword\">throw<\/span> <span class=\"hljs-built_in\">std<\/span>::runtime_error(<span class=\"hljs-string\">\"enqueue on stopped ThreadPool\"<\/span>);\n\n        tasks.emplace(&#91;task]() { (*task)(); });\n    }\n\n    condition.notify_one();\n    <span class=\"hljs-keyword\">return<\/span> res;\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C++<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cpp<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\">Example Usage<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s an example demonstrating how to use the thread pool:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"C++\" data-shcb-language-slug=\"cpp\"><span><code class=\"hljs language-cpp\"><span class=\"hljs-meta\">#<span class=\"hljs-meta-keyword\">include<\/span> <span class=\"hljs-meta-string\">&lt;iostream&gt;<\/span><\/span>\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">int<\/span> <span class=\"hljs-title\">main<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\n    <span class=\"hljs-function\">ThreadPool <span class=\"hljs-title\">pool<\/span><span class=\"hljs-params\">(<span class=\"hljs-number\">4<\/span>)<\/span><\/span>;\n\n    <span class=\"hljs-keyword\">auto<\/span> result1 = pool.enqueue(&#91;] { <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-string\">\"Hello, \"<\/span>; });\n    <span class=\"hljs-keyword\">auto<\/span> result2 = pool.enqueue(&#91;] { <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-string\">\"World!\"<\/span>; });\n\n    <span class=\"hljs-built_in\">std<\/span>::<span class=\"hljs-built_in\">cout<\/span> &lt;&lt; result1.get() &lt;&lt; result2.get() &lt;&lt; <span class=\"hljs-built_in\">std<\/span>::<span class=\"hljs-built_in\">endl<\/span>;\n\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-number\">0<\/span>;\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C++<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cpp<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">6. Implementing Shutdown Procedures<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A proper shutdown procedure ensures all tasks are completed before terminating the threads.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Graceful Shutdown<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To implement a graceful shutdown, modify the destructor to wait for all tasks to finish before stopping the threads.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"C++\" data-shcb-language-slug=\"cpp\"><span><code class=\"hljs language-cpp\">ThreadPool::~ThreadPool() {\n    {\n        <span class=\"hljs-function\"><span class=\"hljs-built_in\">std<\/span>::unique_lock&lt;<span class=\"hljs-built_in\">std<\/span>::mutex&gt; <span class=\"hljs-title\">lock<\/span><span class=\"hljs-params\">(queue_mutex)<\/span><\/span>;\n        stop = <span class=\"hljs-literal\">true<\/span>;\n    }\n\n    condition.notify_all();\n    <span class=\"hljs-keyword\">for<\/span> (<span class=\"hljs-built_in\">std<\/span>::thread &amp;worker : workers)\n        worker.join();\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C++<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cpp<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\">Forcing Shutdown<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Forcing a shutdown might be necessary in some scenarios. Add a method to clear the task queue and stop the threads immediately.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"C++\" data-shcb-language-slug=\"cpp\"><span><code class=\"hljs language-cpp\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">ThreadPool::shutdown<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\n    {\n        <span class=\"hljs-function\"><span class=\"hljs-built_in\">std<\/span>::unique_lock&lt;<span class=\"hljs-built_in\">std<\/span>::mutex&gt; <span class=\"hljs-title\">lock<\/span><span class=\"hljs-params\">(queue_mutex)<\/span><\/span>;\n        stop = <span class=\"hljs-literal\">true<\/span>;\n        <span class=\"hljs-keyword\">while<\/span> (!tasks.empty()) {\n            tasks.pop();\n        }\n    }\n\n    condition.notify_all();\n    <span class=\"hljs-keyword\">for<\/span> (<span class=\"hljs-built_in\">std<\/span>::thread &amp;worker : workers)\n        worker.join();\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C++<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cpp<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">7. Testing the Thread Pool<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Unit Testing<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Write unit tests to verify the thread pool&#8217;s functionality. Use a testing framework like Google Test or Catch2.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Example test case:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"C++\" data-shcb-language-slug=\"cpp\"><span><code class=\"hljs language-cpp\"><span class=\"hljs-meta\">#<span class=\"hljs-meta-keyword\">define<\/span> CATCH_CONFIG_MAIN<\/span>\n<span class=\"hljs-meta\">#<span class=\"hljs-meta-keyword\">include<\/span> <span class=\"hljs-meta-string\">&lt;catch2\/catch.hpp&gt;<\/span><\/span>\n<span class=\"hljs-meta\">#<span class=\"hljs-meta-keyword\">include<\/span> <span class=\"hljs-meta-string\">\"ThreadPool.h\"<\/span><\/span>\n\nTEST_CASE(<span class=\"hljs-string\">\"ThreadPool executes tasks\"<\/span>, <span class=\"hljs-string\">\"&#91;ThreadPool]\"<\/span>) {\n    <span class=\"hljs-function\">ThreadPool <span class=\"hljs-title\">pool<\/span><span class=\"hljs-params\">(<span class=\"hljs-number\">4<\/span>)<\/span><\/span>;\n\n    <span class=\"hljs-keyword\">auto<\/span> result1 = pool.enqueue(&#91;] { <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-number\">1<\/span> + <span class=\"hljs-number\">1<\/span>; });\n    <span class=\"hljs-keyword\">auto<\/span> result2 = pool.enqueue(&#91;] { <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-number\">2<\/span> + <span class=\"hljs-number\">2<\/span>; });\n\n    REQUIRE(result1.get() == <span class=\"hljs-number\">2<\/span>);\n    REQUIRE(result2.get() == <span class=\"hljs-number\">4<\/span>);\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C++<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cpp<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\">Performance Testing<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Measure the performance of your thread pool using benchmarking tools or custom timing code.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"C++\" data-shcb-language-slug=\"cpp\"><span><code class=\"hljs language-cpp\"><span class=\"hljs-meta\">#<span class=\"hljs-meta-keyword\">include<\/span> <span class=\"hljs-meta-string\">&lt;iostream&gt;<\/span><\/span>\n<span class=\"hljs-meta\">#<span class=\"hljs-meta-keyword\">include<\/span> <span class=\"hljs-meta-string\">&lt;chrono&gt;<\/span><\/span>\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">performance_test<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\n    <span class=\"hljs-function\">ThreadPool <span class=\"hljs-title\">pool<\/span><span class=\"hljs-params\">(<span class=\"hljs-number\">4<\/span>)<\/span><\/span>;\n    <span class=\"hljs-keyword\">auto<\/span> start = <span class=\"hljs-built_in\">std<\/span>::chrono::high_resolution_clock::now();\n\n    <span class=\"hljs-built_in\">std<\/span>::<span class=\"hljs-built_in\">vector<\/span>&lt;<span class=\"hljs-built_in\">std<\/span>::<span class=\"hljs-built_in\">future<\/span>&lt;<span class=\"hljs-keyword\">void<\/span>&gt;&gt; results;\n    <span class=\"hljs-keyword\">for<\/span> (<span class=\"hljs-keyword\">int<\/span> i = <span class=\"hljs-number\">0<\/span>; i &lt; <span class=\"hljs-number\">1000<\/span>; ++i) {\n        results.emplace_back(pool.enqueue(&#91;] {\n            <span class=\"hljs-built_in\">std<\/span>::this_thread::sleep_for(<span class=\"hljs-built_in\">std<\/span>::chrono::milliseconds(<span class=\"hljs-number\">10<\/span>));\n        }));\n    }\n\n    <span class=\"hljs-keyword\">for<\/span> (<span class=\"hljs-keyword\">auto<\/span> &amp;&amp;result : results)\n        result.get();\n\n    <span class=\"hljs-keyword\">auto<\/span> end = <span class=\"hljs-built_in\">std<\/span>::chrono::high_resolution_clock::now();\n    <span class=\"hljs-built_in\">std<\/span>::chrono::duration&lt;<span class=\"hljs-keyword\">double<\/span>&gt; duration = end - start;\n    <span class=\"hljs-built_in\">std<\/span>::<span class=\"hljs-built_in\">cout<\/span> &lt;&lt; <span class=\"hljs-string\">\"Time taken: \"<\/span> &lt;&lt; duration.count() &lt;&lt; <span class=\"hljs-string\">\" seconds\"<\/span> &lt;&lt; <span class=\"hljs-built_in\">std<\/span>::<span class=\"hljs-built_in\">endl<\/span>;\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C++<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cpp<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">8. Advanced Features<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Dynamic Thread Management<\/strong> &#8211; Allow the thread pool to adjust the number of worker threads dynamically based on the load.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Task Prioritization<\/strong> &#8211; Implement a priority queue to manage tasks with different priorities.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Work Stealing<\/strong> &#8211; Allow idle threads to steal tasks from busy threads to balance the load.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example: Dynamic Thread Management<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Modify the thread pool to allow adding or removing worker threads dynamically.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"C++\" data-shcb-language-slug=\"cpp\"><span><code class=\"hljs language-cpp\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">ThreadPool<\/span> {<\/span>\n<span class=\"hljs-keyword\">public<\/span>:\n    <span class=\"hljs-comment\">\/\/ Other methods...<\/span>\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">addThread<\/span><span class=\"hljs-params\">()<\/span><\/span>;\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">removeThread<\/span><span class=\"hljs-params\">()<\/span><\/span>;\n};\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">ThreadPool::addThread<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\n    <span class=\"hljs-function\"><span class=\"hljs-built_in\">std<\/span>::thread <span class=\"hljs-title\">worker<\/span><span class=\"hljs-params\">(&#91;<span class=\"hljs-keyword\">this<\/span>] {\n        <span class=\"hljs-keyword\">while<\/span> (<span class=\"hljs-literal\">true<\/span>) {\n            <span class=\"hljs-built_in\">std<\/span>::function&lt;<span class=\"hljs-keyword\">void<\/span>()&gt; task;\n\n            {\n                <span class=\"hljs-built_in\">std<\/span>::unique_lock&lt;<span class=\"hljs-built_in\">std<\/span>::mutex&gt; lock(<span class=\"hljs-keyword\">this<\/span>-&gt;queue_mutex);\n                <span class=\"hljs-keyword\">this<\/span>-&gt;condition.wait(lock, &#91;<span class=\"hljs-keyword\">this<\/span>] {\n                    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">this<\/span>-&gt;stop || !<span class=\"hljs-keyword\">this<\/span>-&gt;tasks.empty();\n                });\n\n                <span class=\"hljs-keyword\">if<\/span> (<span class=\"hljs-keyword\">this<\/span>-&gt;stop &amp;&amp; <span class=\"hljs-keyword\">this<\/span>-&gt;tasks.empty())\n                    <span class=\"hljs-keyword\">return<\/span>;\n\n                task = <span class=\"hljs-built_in\">std<\/span>::move(<span class=\"hljs-keyword\">this<\/span>-&gt;tasks.front());\n                <span class=\"hljs-keyword\">this<\/span>-&gt;tasks.pop();\n            }\n\n            task();\n        }\n    })<\/span><\/span>;\n\n    workers.push_back(<span class=\"hljs-built_in\">std<\/span>::move(worker));\n}\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">ThreadPool::removeThread<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\n    {\n        <span class=\"hljs-function\"><span class=\"hljs-built_in\">std<\/span>::unique_lock&lt;<span class=\"hljs-built_in\">std<\/span>::mutex&gt; <span class=\"hljs-title\">lock<\/span><span class=\"hljs-params\">(queue_mutex)<\/span><\/span>;\n        <span class=\"hljs-keyword\">if<\/span> (!workers.empty()) {\n            stop = <span class=\"hljs-literal\">true<\/span>;\n            condition.notify_one();\n            workers.back().join();\n            workers.pop_back();\n            stop = <span class=\"hljs-literal\">false<\/span>;\n        }\n    }\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C++<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cpp<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">9. Performance Considerations<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Optimal Number of Threads<\/strong> &#8211; Choosing the optimal number of threads depends on the nature of your tasks and the hardware. A general rule is to have as many threads as there are hardware threads (cores).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Avoiding Deadlocks<\/strong>&#8211; Ensure that your tasks do not cause deadlocks by carefully managing locks and avoiding circular dependencies.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Minimizing Lock Contention<\/strong> &#8211; Minimize the use of locks or use lock-free data structures to reduce contention and improve performance.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example: Optimal Number of Threads<\/h3>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"C++\" data-shcb-language-slug=\"cpp\"><span><code class=\"hljs language-cpp\"><span class=\"hljs-meta\">#<span class=\"hljs-meta-keyword\">include<\/span> <span class=\"hljs-meta-string\">&lt;thread&gt;<\/span><\/span>\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">int<\/span> <span class=\"hljs-title\">main<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\n    <span class=\"hljs-keyword\">unsigned<\/span> <span class=\"hljs-keyword\">int<\/span> num_threads = <span class=\"hljs-built_in\">std<\/span>::thread::hardware_concurrency();\n    <span class=\"hljs-function\">ThreadPool <span class=\"hljs-title\">pool<\/span><span class=\"hljs-params\">(num_threads)<\/span><\/span>;\n\n    <span class=\"hljs-comment\">\/\/ Enqueue tasks...<\/span>\n\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-number\">0<\/span>;\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C++<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cpp<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">10. Conclusion<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Creating a custom thread pool in C++ involves understanding and implementing several key concepts: thread management, task queuing, synchronization, and graceful shutdown. By following this tutorial, you should now have a solid foundation to build and optimize your own thread pool for various applications.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Creating a custom thread pool in C++ is an essential skill for developers who need to manage multiple threads efficiently. This tutorial will guide you through the process of designing and implementing a thread pool from scratch. By the end, you will have a solid understanding of thread management and how to optimize concurrent tasks [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_genesis_hide_title":false,"_genesis_hide_breadcrumbs":false,"_genesis_hide_singular_image":false,"_genesis_hide_footer_widgets":false,"_genesis_custom_body_class":"","_genesis_custom_post_class":"","_genesis_layout":"","_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[9,4],"tags":[],"class_list":["post-2101","post","type-post","status-publish","format-standard","category-cplusplus","category-programming-languages","entry"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.6 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>How to Create a Custom Thread Pool in C++<\/title>\n<meta name=\"description\" content=\"A thread pool is a collection of pre-initialized threads that stand by to perform tasks. Instead of creating and destroying threads for each task\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.w3computing.com\/articles\/how-to-create-a-custom-thread-pool-in-cpp\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to Create a Custom Thread Pool in C++\" \/>\n<meta property=\"og:description\" content=\"A thread pool is a collection of pre-initialized threads that stand by to perform tasks. Instead of creating and destroying threads for each task\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.w3computing.com\/articles\/how-to-create-a-custom-thread-pool-in-cpp\/\" \/>\n<meta property=\"article:published_time\" content=\"2024-07-10T20:32:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-07-10T20:35:41+00:00\" \/>\n<meta name=\"author\" content=\"w3compadmin\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"w3compadmin\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"TechArticle\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/how-to-create-a-custom-thread-pool-in-cpp\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/how-to-create-a-custom-thread-pool-in-cpp\\\/\"},\"author\":{\"name\":\"w3compadmin\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#\\\/schema\\\/person\\\/a550b3e20d78bb4f79b7c6b7b53f0561\"},\"headline\":\"How to Create a Custom Thread Pool in C++\",\"datePublished\":\"2024-07-10T20:32:00+00:00\",\"dateModified\":\"2024-07-10T20:35:41+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/how-to-create-a-custom-thread-pool-in-cpp\\\/\"},\"wordCount\":720,\"articleSection\":[\"C++\",\"Programming Languages\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/how-to-create-a-custom-thread-pool-in-cpp\\\/\",\"url\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/how-to-create-a-custom-thread-pool-in-cpp\\\/\",\"name\":\"How to Create a Custom Thread Pool in C++\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#website\"},\"datePublished\":\"2024-07-10T20:32:00+00:00\",\"dateModified\":\"2024-07-10T20:35:41+00:00\",\"author\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#\\\/schema\\\/person\\\/a550b3e20d78bb4f79b7c6b7b53f0561\"},\"description\":\"A thread pool is a collection of pre-initialized threads that stand by to perform tasks. Instead of creating and destroying threads for each task\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/how-to-create-a-custom-thread-pool-in-cpp\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/how-to-create-a-custom-thread-pool-in-cpp\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/how-to-create-a-custom-thread-pool-in-cpp\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Articles Home\",\"item\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Programming Languages\",\"item\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/programming-languages\\\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"C++\",\"item\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/programming-languages\\\/cplusplus\\\/\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"How to Create a Custom Thread Pool in C++\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#website\",\"url\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/\",\"name\":\"Developer Articles Hub\",\"description\":\"\",\"alternateName\":\"Developer Articles\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#\\\/schema\\\/person\\\/a550b3e20d78bb4f79b7c6b7b53f0561\",\"name\":\"w3compadmin\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/wp-content\\\/litespeed\\\/avatar\\\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266\",\"url\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/wp-content\\\/litespeed\\\/avatar\\\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266\",\"contentUrl\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/wp-content\\\/litespeed\\\/avatar\\\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266\",\"caption\":\"w3compadmin\"},\"sameAs\":[\"http:\\\/\\\/w3computing.com\\\/articles\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to Create a Custom Thread Pool in C++","description":"A thread pool is a collection of pre-initialized threads that stand by to perform tasks. Instead of creating and destroying threads for each task","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.w3computing.com\/articles\/how-to-create-a-custom-thread-pool-in-cpp\/","og_locale":"en_US","og_type":"article","og_title":"How to Create a Custom Thread Pool in C++","og_description":"A thread pool is a collection of pre-initialized threads that stand by to perform tasks. Instead of creating and destroying threads for each task","og_url":"https:\/\/www.w3computing.com\/articles\/how-to-create-a-custom-thread-pool-in-cpp\/","article_published_time":"2024-07-10T20:32:00+00:00","article_modified_time":"2024-07-10T20:35:41+00:00","author":"w3compadmin","twitter_card":"summary_large_image","twitter_misc":{"Written by":"w3compadmin","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"TechArticle","@id":"https:\/\/www.w3computing.com\/articles\/how-to-create-a-custom-thread-pool-in-cpp\/#article","isPartOf":{"@id":"https:\/\/www.w3computing.com\/articles\/how-to-create-a-custom-thread-pool-in-cpp\/"},"author":{"name":"w3compadmin","@id":"https:\/\/www.w3computing.com\/articles\/#\/schema\/person\/a550b3e20d78bb4f79b7c6b7b53f0561"},"headline":"How to Create a Custom Thread Pool in C++","datePublished":"2024-07-10T20:32:00+00:00","dateModified":"2024-07-10T20:35:41+00:00","mainEntityOfPage":{"@id":"https:\/\/www.w3computing.com\/articles\/how-to-create-a-custom-thread-pool-in-cpp\/"},"wordCount":720,"articleSection":["C++","Programming Languages"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/www.w3computing.com\/articles\/how-to-create-a-custom-thread-pool-in-cpp\/","url":"https:\/\/www.w3computing.com\/articles\/how-to-create-a-custom-thread-pool-in-cpp\/","name":"How to Create a Custom Thread Pool in C++","isPartOf":{"@id":"https:\/\/www.w3computing.com\/articles\/#website"},"datePublished":"2024-07-10T20:32:00+00:00","dateModified":"2024-07-10T20:35:41+00:00","author":{"@id":"https:\/\/www.w3computing.com\/articles\/#\/schema\/person\/a550b3e20d78bb4f79b7c6b7b53f0561"},"description":"A thread pool is a collection of pre-initialized threads that stand by to perform tasks. Instead of creating and destroying threads for each task","breadcrumb":{"@id":"https:\/\/www.w3computing.com\/articles\/how-to-create-a-custom-thread-pool-in-cpp\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.w3computing.com\/articles\/how-to-create-a-custom-thread-pool-in-cpp\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.w3computing.com\/articles\/how-to-create-a-custom-thread-pool-in-cpp\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Articles Home","item":"https:\/\/www.w3computing.com\/articles\/"},{"@type":"ListItem","position":2,"name":"Programming Languages","item":"https:\/\/www.w3computing.com\/articles\/programming-languages\/"},{"@type":"ListItem","position":3,"name":"C++","item":"https:\/\/www.w3computing.com\/articles\/programming-languages\/cplusplus\/"},{"@type":"ListItem","position":4,"name":"How to Create a Custom Thread Pool in C++"}]},{"@type":"WebSite","@id":"https:\/\/www.w3computing.com\/articles\/#website","url":"https:\/\/www.w3computing.com\/articles\/","name":"Developer Articles Hub","description":"","alternateName":"Developer Articles","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.w3computing.com\/articles\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/www.w3computing.com\/articles\/#\/schema\/person\/a550b3e20d78bb4f79b7c6b7b53f0561","name":"w3compadmin","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.w3computing.com\/articles\/wp-content\/litespeed\/avatar\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266","url":"https:\/\/www.w3computing.com\/articles\/wp-content\/litespeed\/avatar\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266","contentUrl":"https:\/\/www.w3computing.com\/articles\/wp-content\/litespeed\/avatar\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266","caption":"w3compadmin"},"sameAs":["http:\/\/w3computing.com\/articles"]}]}},"featured_image_src":null,"featured_image_src_square":null,"author_info":{"display_name":"w3compadmin","author_link":"https:\/\/www.w3computing.com\/articles\/author\/w3compadmin\/"},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/posts\/2101","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/comments?post=2101"}],"version-history":[{"count":1,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/posts\/2101\/revisions"}],"predecessor-version":[{"id":2102,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/posts\/2101\/revisions\/2102"}],"wp:attachment":[{"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/media?parent=2101"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/categories?post=2101"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/tags?post=2101"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}