This is copied from my answer to another very similar post, hope this helps:
1) Start with the maximum number of threads that the system can support:
int Num_Threads = thread::hardware_concurrency();
2) For the effective implementation of the thread pool, as soon as the threads are created in accordance with Num_Threads, it is better not to create new ones and not destroy the old ones (by combining). This will lead to a decrease in performance, it may even make your application run slower than the serial version.
Each C ++ 11 thread should work in its function with an infinite loop, constantly waiting for new tasks to be received and launched.
Here's how to attach such a function to a thread pool:
int Num_Threads = thread::hardware_concurrency(); vector<thread> Pool; for(int ii = 0; ii < Num_Threads; ii++) { Pool.push_back(thread(Infinite_loop_function));}
3) Function Infinite_loop_function
This is a while (true) loop waiting for a task queue
void The_Pool:: Infinite_loop_function() { while(true) { { unique_lock<mutex> lock(Queue_Mutex); condition.wait(lock, []{return !Queue.empty() || therminate_pool}); Job = Queue.front(); Queue.pop(); } Job();
4) Make a function to add work to your turn
void The_Pool:: Add_Job(function<void()> New_Job) { { unique_lock<mutex> lock(Queue_Mutex); Queue.push(New_Job); } condition.notify_one(); }
5) Bind an arbitrary function to your queue
Pool_Obj.Add_Job(std::bind(&Some_Class::Some_Method, &Some_object));
Once you integrate these ingredients, you will have your own dynamic thread pool. These threads always work, waiting for the job to complete.
I apologize if there are any syntax errors, I typed this code and I have bad memory. Sorry that I cannot provide you with the full thread pool code that would disrupt my work.
Edit: to end the pool, call the shutdown () method:
XXXX::shutdown(){ { unique_lock<mutex> lock(threadpool_mutex); terminate_pool = true;} // use this flag in condition.wait condition.notify_all(); // wake up all threads. // Join all threads. for(std::thread &every_thread : thread_vector) { every_thread.join();} thread_vector.empty(); stopped = true; // use this flag in destructor, if not set, call shutdown()
}