degate  0.1.2
ThreadPool.h
Go to the documentation of this file.
00001 #ifndef __THREADPOOL_H__
00002 #define __THREADPOOL_H__
00003 
00004 #include <boost/thread.hpp>
00005 #include <boost/function.hpp>
00006 #include <boost/foreach.hpp>
00007 #include <iostream>
00008 #include <memory>
00009 
00010 
00011 template <typename FunctionType>
00012 class ThreadPool {
00013 
00014   typedef std::shared_ptr<boost::thread> thread_shptr;
00015 
00016 private:
00017   unsigned int max_n;
00018 
00019   std::list<FunctionType> task_queue;
00020   std::list<thread_shptr> running;
00021 
00022   void spawn() {
00023       while(running.size() < max_n && task_queue.size() > 0 ) {
00024         FunctionType f(task_queue.front());
00025         task_queue.pop_front();
00026 
00027         boost::thread * p = new boost::thread(f);
00028         thread_shptr t = thread_shptr(p);
00029         running.push_back(t);
00030       }
00031   }
00032 
00033 public:
00034 
00035   ThreadPool(unsigned int n = 4) : max_n(n) {
00036   }
00037 
00038   ~ThreadPool() {
00039     wait();
00040   }
00041 
00042 
00043   void add(FunctionType f) {
00044     task_queue.push_back(f);
00045   }
00046 
00047   void wait() {
00048 
00049     while(task_queue.size() > 0 || running.size() > 0) {
00050 
00051       spawn();
00052 
00053       for(std::list<thread_shptr>::iterator iter = running.begin();
00054           iter != running.end(); ++iter) {
00055 
00056         //std::cout << "timed wait\n";
00057         if((*iter)->timed_join(boost::posix_time::millisec( 1000 )   )) {
00058           std::list<thread_shptr>::iterator i(iter);
00059           ++iter;
00060           running.erase(i);
00061         }
00062 
00063       }
00064 
00065 
00066     }
00067 
00068   }
00069 
00070 
00071 };
00072 
00073 #endif