A simple thread pool implementation in C++
To use the thread pool in your project, you simply include the header where it's needed and add the .cpp implentation file in your compilation. Make sure that the header file is visible from the .cpp file. The preferred way of doing this is using the -I option of gcc/g++.
You also have to add the pthread library during the linking step, since the thread pool uses POSIX threads.
#include<iostream>
#include"thread_pool.h"usingnamespacestd;// Extending the base thread_pool::task class to provide void run() implementation.classmy_task : publicthread_pool::task {
private:int i;
public:my_task(int i) : i(i) {}
voidrun() {
cout << "Hello from thread, i = " << i << endl;
}
};
intmain() {
// Creating a thread pool with 4 threads.
thread_pool thread_pool(4);
// Adding jobs in the thread pool.for (int i = 0; i < 50; i++)
thread_pool.add_task(newmy_task(i));
// Thread pool destructor will wait here, until all jobs are completed.
}This project is licensed under the MIT License - see the LICENSE file for details