Search code examples
c++multithreadingboostthreadpoolboost-thread

C++ Thread Pool


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.


Solution

  • 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.