C++ Thread Pool [closed] C++ Thread Pool [closed] multithreading multithreading

C++ Thread Pool [closed]


I think it is still not accepted into Boost, but a good staring point:threadpool. Some example of usage, from the web site:

#include "threadpool.hpp"using namespace boost::threadpool;// Some example tasksvoid first_task(){  ...}void second_task(){  ...}void third_task(){  ...}void execute_with_threadpool(){  // Create a thread pool.  pool tp(2);  // Add some tasks to the pool.  tp.schedule(&first_task);  tp.schedule(&second_task);  tp.schedule(&third_task);  // Leave this function and wait until all tasks are finished.}

The argument "2" to the pool indicates the number of threads. In this case, the destruction of tp waits for all threads to finish.


You might want to look at http://threadpool.sourceforge.net/

It is not hard to implement thread pool yourself using Boost.Thread. Depending on the task, you might want to use lock-free container for the queue instead of one from Standard Template Library. For example, fifo container from lock free library.

Good luck!


I've written a small example here. Basically what you need to do is to implement this piece of code:

asio::io_service io_service;boost::thread_group threads;auto_ptr<asio::io_service::work> work(new asio::io_service::work(io_service)); // Spawn enough worker threadsint cores_number = boost::thread::hardware_concurrency();for (std::size_t i = 0; i < cores_number; ++i){    threads.create_thread(boost::bind(&asio::io_service::run, &io_service));}// Post the tasks to the io_servicefor(vector<string>::iterator it=tasks.begin();it!=tasks.end();it++){   io_service.dispatch(/* YOUR operator()() here */);}work.reset();