EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

C++ Thread Pool

By Yashi GoyalYashi Goyal

Home » Software Development » C++ Thread Pool

C++ Thread Pool

Definition of C++ Thread Pool

Threadpool in C++ is basically a pool having a fixed number of threads used when we want to work multiple tasks together (run multiple threads concurrently). This thread sits idle in the thread pool when there are no tasks and when a task arrives, it is sent to the thread pool and gets assigned to the thread. Pending tasks will remain in the queue waiting for a thread to get free. In C++ there is no specific library for thread pool, but it provides various methods in the API which the programmer can use and create the one according to the requirements.

Syntax:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Below given is the basic syntax of using the C++ thread pool:

using namespace std;
// initializing the number of threads
int count_threads = thread: : hardware_concurrency();
int main()
{
thread_pool  pool;
// queuing the work/ task to thread pool queue and store the future
auto res = pool.enqueue([](int x) { return x; }, 42);
//printing the output on console
cout << res.get() << endl;
}

In the above syntax,

  • thread: hardware_concurrency(): It basically initializes the fixed number of threads that are going to work on the desired task.
  • Pool.enqueue: It will enqueue the task request in the pool which needs to be processed.
  • res.get(): It is used to get the result from the future.

How Thread Pools Works in C++?

It is nice to work with the thread pools when we have a large number of tasks and we want them to execute parallelly. It reduces the overhead of the creation of threads every time and too much of threads reduce the overall speed of the system. There is no specific library in C++ which provides the thread pool so the programmer has to create it is own depending on the requirements.

Below given is the step by step procedure of the working of thread in the thread pool in C++ :

1. Threadpool class is initialized with some fixed number of worker threads which can be done by thread::hardware_concurrency() function. Initially we can also create zero (0) threads when there is no work to be done. These created threads wait on the condition variable.

Popular Course in this category
C++ Training (4 Courses, 5 Projects, 4 Quizzes)4 Online Courses | 5 Hands-on Projects | 37+ Hours | Verifiable Certificate of Completion | Lifetime Access | 4 Quizzes with Solutions
4.5 (5,213 ratings)
Course Price

View Course

Related Courses
Java Training (40 Courses, 29 Projects, 4 Quizzes)C Programming Training (3 Courses, 5 Project)

2. When a new task arrives, it is first put in the queue of pending work, and the following steps are performed:

  • It is first checked whether the thread in the thread pool is free or not.
  • If the thread is free, it is woken up by signaling the condition variable. It then takes off the work from the task queue to perform the desired task. Once the task is completed, it then goes back to that queue for more work.
  • Once the thread performs the desired task, the thread again waits on the condition variable to show its state.

3. In a thread pool, objects are destroyed only when the destructor of thread pool class is called by the programmer.

Examples

One can implement the thread pool using the C++ APIs according to the requirements. But there are various challenges that the user/programmer faces while designing it. Some of them can be a number of threads that should be created in order to have efficient performance, techniques to be used to allocate the task to the thread, whether the waiting for the completion of tasks should be done or not, waiting for task queue techniques, etc.

One of the simplest implementations of the thread pool is given below:

#include <iostream>
#include <cstdlib>
#include <thread>
#include create_pool.h
using namespace std;
#define trace(x)
// function to define the number of threads
auto int num_threads = thread::hardware_concurrency();
//checking condition of the number of threads available
// if the number of threads is 0
if(num_threads == 0)
{
num_threads =1;
}
const int total_task = 20000;
//main logic inside the main function with 2 arguments
int main(int argc, char** argv)
{
srand((unsigned int)time(NULL));
//creating a thread pool
thread_pool p;
//enqueue function used to queue the request that needs to be processed by
//thread pool and retrieving the output in 'output' variable
auto output = p.enqueue_task([](int x) { return x; }, 0xFF);
output.get();
//processing the request
for(int x = 1; x <= num_threads; x++)
p.enqueue_work([](int thread_number) {
int work_out = 0;
int work = total_task + (rand() % (total_task));
trace("Thread " << thread_number << "is going to start " << work );
for(int y = 0; y < work; y++)
work_out += rand();
trace("Execution of " << thread_number << " is ended");
}, x);
return 1;
}

Explanation:

In the above code, firstly the threads are created using ‘thread::hardware_concurrency()’ function and checked if the number of threads is 0, then it makes 1 active thread available. Function ‘enqueue_task() is used to queue the task that needs to be processed in the pool. The results of them are stored in the output variable. In order to retrieve the exact data from it, the get() function is used. Finally, the processing of thread requests is done using each request at a time in the ‘for’ loop and there in between processing and end is displayed on the console to make it easy to understand the flow.

This is the basic C++ code providing a glimpse of how the thread pool is implemented in a normal C++ application. One needs to implement a lot of things while working in the real application checking various conditions. One can also add the mutex, which is listening from another application like database, disk, etc.

Moreover, create_pool.h file included in the above code needs to be created according to the requirements performing the basic functions, like creating a pool using the blocking_queue method, destruction of threads, etc.

One needs to be at the expert level and understand all the in-depth working of threads and the basic functions of C++ and their implementation before working on it.

Conclusion

The above description clearly explains what is C++ thread pool is and how it can be used in a program. Thread pools are important to use in an application as it becomes easy and efficient to use the threads. Moreover, it does not keep the system overloaded as the user/ programmer can limit the number of threads and the tasks assigned to them. Tasks will remain in the queue and will execute once the thread becomes free.

Recommended Articles

This is a guide to C++ Thread Pool. Here we discuss the Definition of C++ Thread Pool with How Thread Pools Work in C++ with programming examples?. You may also have a look at the following articles to learn more –

  1. C++ Mutable
  2. C++ reserve()
  3. C++ push_back
  4. C++ find()

C++ Training (4 Courses, 5 Projects, 4 Quizzes)

4 Online Courses

5 Hands-on Projects

37+ Hours

Verifiable Certificate of Completion

Lifetime Access

4 Quizzes with Solutions

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
C plus plus Programming Tutorial
  • Advanced
    • C++ namespace
    • Encapsulation in C++
    • Access Modifiers in C++
    • Abstract Class in C++
    • C++ Class and Object
    • What is Template Class in C++?
    • C++ Algorithm
    • Data Structures and Algorithms C++
    • C++ Garbage Collection
    • Virtual Keyword in C++
    • Access Specifiers in C++
    • Storage Class in C++
    • Call by Value in C++
    • Multimap in C++
    • C++ Multiset
    • C++ Lambda Expressions
    • Stack in C++
    • C++ Static
    • C++ static_cast
    • Deque in C++
    • C++ Vector Functions
    • C++ 2D Vector
    • C++ List
    • C++ Mutable
    • Enum in C++
    • Abstraction in C++
    • Signal in C++
    • C++ Queue
    • Priority Queue in C++
    • Regular Expressions in C++
    • C++ Hash Table
    • C++ Expression
    • File Handling in C++
    • C++ Stream
    • ifstream in C++
    • C++ ofstream
    • C++ fstream
    • C++ Read File
    • C++ iomanip
    • Macros in C++
    • Templates in C++
    • C++ setprecision
    • C++ Int to String
    • C++ thread( )
    • C++ Thread Pool
    • C++ thread_local
  • Basic
    • Introduction To C++
    • What is C++
    • Features of C++
    • Applications of C++
    • Best C++ Compiler
    • C++ Data Types
    • C++ Double
    • C++ unsigned int
    • User Defined Data Types in C++
    • Variables in C++
    • C++ Keywords
    • Pointers in C++
    • C++ Void Pointer
    • Function Pointer in C++
    • Iterator in C++
    • C++ Commands
    • Object in C++
    • C++ Literals
    • C++ Reference
    • C++ Undefined Reference
    • String in C++
    • C++ Programming Language (Basics)
    • C++ Identifiers
    • C++ Header Files
    • Type Casting in C++
    • C++ Formatter
  • Operators
    • C++ Operators
    • Arithmetic Operators in C++
    • Assignment Operators in C++
    • Bitwise Operators in C++
    • Relational Operators in C++
    • Boolean Operators in C++
    • Unary Operators in C++
    • C++ Operator[]
    • Operator Precedence in C++
    • C++ operator=()
  • Control Statements
    • Control Statement in C++
    • if else Statement in C++
    • Else If in C++
    • Nested if in C++
    • Continue Statement in C++
    • Break Statement in C++
    • Switch Statement in C++
    • goto Statement in C++
    • C++ Struct
    • Loops in C++
    • Do While Loop in C++
    • Nested Loop in C++
  • Functions
    • C++ getline()
    • C++ String Functions
    • Math Functions in C++
    • Friend Function in C++
    • Recursive Function in C++
    • Virtual Functions in C++
    • strcat() in C++
    • swap() in C++
    • strcmp() in C++
    • ceil function in C++
    • C++ begin()
    • size() in C++
    • C++ test()
    • C++ any()
    • C++ Bitset
    • C++ find()
    • C++?Aggregation
    • C++?String append
    • C++ String Copy
    • C++ end()
    • C++ endl
    • C++ push_back
    • C++ shuffle()
    • malloc() in C++
    • C++ reserve()
    • C++ unique()
    • C++ sort()
    • C++ find_if()
    • Reflection in C++
    • C++ replace()
    • C++ search()
    • C++ Memset
    • C++ size_t
    • C++ Substring
    • C++ Max
    • C++ absolute value
    • C++ memcpy
    • C++ wchar_t
    • C++ free()
    • C++ pair
    • C++ this
    • C++ sizeof()
    • C++ Move Semantics
  • Array
    • Arrays in C++
    • 2D Arrays in C++
    • 3D Arrays in C++
    • Multi-Dimensional Arrays in C++
    • C++ Array Functions
    • String Array in C++
    • C++ Length of Array
    • C++ arraylist
  • Constuctor and Destructor
    • Constructor and Destructor in C++
    • Constructor in C++
    • Destructor in C++
    • Copy Constructor in C++
    • Parameterized Constructor in C++
  • Overloading and overriding
    • Overloading and Overriding in C++
    • Overloading in C++
    • Overriding in C++
    • Function Overloading in C++
    • Function Overriding in C++
    • Method Overloading in C++
  • Inhertiance
    • Types of Inheritance in C++
    • Single Inheritance in C++
    • Multiple Inheritance in C++
    • Hierarchical Inheritance in C++
    • Multilevel Inheritance in C++
    • Hybrid Inheritance in C++
  • Sorting
    • Sorting in C++ 
    • Heap Sort in C++
    • C++ Vector Sort
    • Insertion Sort in C++
    • Selection Sort in C++
    • C++ QuickSort
    • Sort string C++
  • Programs
    • Patterns in C++
    • Star Patterns In c++
    • Swapping in C++
    • Reverse Number in C++
    • Palindrome Program in C++
    • Palindrome in C++
    • Factorial Program in C++
    • Fibonacci Series in C++
    • Square Root in C++
    • Random Number Generator in C++
    • Prime Number in C++
    • Leap Year Program in C++
    • Anagram in C++
    • Armstrong Number in C++
    • Reverse String in C++
    • Socket Programming in C++
    • Matrix Multiplication in C++
    • C++ using vs typedef
    • C++ vector vs list
    • C++ vector vs array
  • Interview question
    • C++ Interview Questions
    • Multithreading Interview Questions C++

Related Courses

C++ Training Course

Java Training Course

C Programming Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - C++ Training (4 Courses, 5 Projects, 4 Quizzes) Learn More