C++ Boost

Boost.Threads

Header <boost/thread/thread_pool.hpp>


Contents

Introduction
Classes
Class thread_pool
Class thread_pool synopsis
Class thread_pool constructors and destructor
Class thread_pool modifier functions
Example(s)

Introduction

Include the header <boost/thread/thread_pool.hpp> to define the thread_pool class.

Classes

Class thread_pool

The thread_pool class provides an interface for running jobs on a dynamically managed set of worker threads called a pool.  When a job is added, it can execute on any available thread in the pool.  This class controls both the maximum and minimum number of threads in the pool.  If a thread in the pool is sitting idle for a period of time, it will exit unless by exiting the number of threads would dip below the minimum. Thread pools provide an optimization over creating a new thread for each job since the pool can often remove the overhead of thread creation.

Class thread_pool synopsis

namespace boost
{
    class thread_pool : boost::noncopyable // Exposition only.
        // Class thread meets the NonCopyable requirement.
    {
    public:
        thread_pool(int max_threads=std::numeric_limits<int>::max(), 
                    int min_threads=0,
                    int timeout_secs=5); 
        ~thread_pool();

        void add(const boost::function0<void> &job);
        void join();
        void cancel();
        void detach();
    };
};

Class thread_pool constructors and destructor

thread_pool(int max_threads=std::numeric_limits<int>::max(), 
            int min_threads=0,
            int timeout_secs=5);
Effects: Constructs a thread pool object and starts min_threads threads running in the pool.
~thread_pool();
Effects: Calls join() if neither join() nor detach() were called previously for this thread_pool.  If detach() was not called, destroys all resources associated with the threads in the pool and with the queue of jobs still waiting to be executed.

Class thread_pool modifier functions

void add(const boost::function0<void>& job);
Effects: Adds job to the thread_pool object's list of jobs waiting to be executed.  If any threads in the pool are idle, the job will be execute as soon as the idle thread is scheduled by the operating system.  If no threads are idle and the number of threads in the pool is less than the maximum number provided to the constructor, an additional thread is created and added to the pool.  That new thread will execute this job as soon as it is scheduled by the operating system.  If no threads are idle and the thread count is at the maximum, this job will be queued until a thread becomes available.  Currently, queued jobs are processed in FIFO order.
Throws: std::runtime_error if join() or detach() have previously been called for this thread_pool object.
void detach();
Effects: Relinquishes control of the pool of threads by this thread_pool object.  Any threads in the pool will continue to run and continue to process any queued jobs, but no new threads will be created, and any subsequent attempts to add new jobs will result in an exception.
Throws: std::runtime_error if join() has previously been called for this thread_pool object.
void cancel();
Effects: Removes all queued jobs from the thread_pool's internal queue, and calls cancel() on all boost::thread objects in the pool.  The specific behavior of those threads will be dictated by their cancellation behavior - the pool threads may be executing a user's job that deferrs cancellation, for example.
Throws: std::runtime_error if join() or detach() have previously been called for this thread_pool object.
Note: for the current version (1.27.0) of Boost.Threads, thread::cancel() is not provided.  This function -will- clear out all queued jobs, but any currently executing jobs will not be cancelled.
void join();
Effects: Waits until all queued jobs are completed by the thread pool, and then join()s will all of the threads in the pool.  When join() returns, no running threads will remain in the pool, and this object is invalid for anything except destruction.  Any calls to cancel(), join(), detach(), or add() will result in an exception.

Example(s)

#include <boost/thread/thread_pool.hpp> 
#include <boost/thread/mutex.hpp> 
#include <iostream> 

boost::mutex io_mutex; 

class job_adapter {
public: 
    job_adapter(void (*func)(int), int param) :
_func(func), _param(param){ }
        void operator()() const { _func(_param); }
private:
   void (*_func)(int);
   int _param; 
}; 
   
void simple_job(int param) 
{ 
    boost::mutex::scoped_lock l(io_mutex); 
    std::cout << param << " squared is " << (param*param) << "\n";
} 

int main(int argc, char* argv[]) 
{ 
    boost::thread_pool tp;
    for (int i = 1; i <= 10; ++i) 
        tp.add(simple_job); 
    tp.join();
	return 0;
}

Typical output would be:

1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
7 squared is 49
6 squared is 36
8 squared is 64
10 squared is 100
9 squared is 81

While the jobs are dispatched in the order they are received, the scheduling of the individual threads in the pool is platform-dependent.

Revised 05 November, 2001

© Copyright William E. Kempf, David Moore 2001-2002. All Rights Reserved.

Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. William E. Kempf makes no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty.