|
|
Boost.ThreadsHeader <boost/thread/thread_pool.hpp> |
thread_poolthread_pool synopsisthread_pool constructors and destructorthread_pool modifier functionsInclude the header <boost/thread/thread_pool.hpp> to define the thread_pool class.
thread_poolThe 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.
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();
};
};
thread_pool constructors and destructor
thread_pool(int max_threads=std::numeric_limits<int>::max(),
int min_threads=0,
int timeout_secs=5);
~thread_pool();
thread_pool modifier
functionsvoid add(const boost::function0<void>& job);
void detach();
void cancel();
void join();
#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.