C++ Thread Pool

Amir Rachum picture Amir Rachum · Oct 21, 2010 · Viewed 46.5k times · Source

What is a good open source implementation of a thread pool for C++ to use in production code (something like boost)?

Please provide either your own example code or a link to example code usage.

Answer

Diego Sevilla picture Diego Sevilla · Oct 21, 2010

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 tasks
void 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.