Choreonoid  1.5
ThreadPool.h
Go to the documentation of this file.
1 
2 #ifndef CNOID_UTIL_THREAD_POOL_H
3 #define CNOID_UTIL_THREAD_POOL_H
4 
5 #include <queue>
6 #include <boost/thread.hpp>
7 #include <boost/function.hpp>
8 
9 namespace cnoid {
10 
12 {
13 private:
14  std::queue<boost::function<void()> > queue;
15  boost::thread_group group;
16  boost::mutex mutex;
17  boost::condition_variable condition;
18  bool isDestroying;
19 
20 public:
21  ThreadPool(int size = 1) {
22  isDestroying = false;
23  for(int i = 0; i < size; i++){
24  group.create_thread(boost::bind(&ThreadPool::run, this));
25  }
26  }
27 
29  {
30  boost::mutex::scoped_lock lock(mutex);
31  isDestroying = true;
32  condition.notify_all();
33  }
34  group.join_all();
35  }
36 
37 
38  void start(boost::function<void()> f) {
39  boost::mutex::scoped_lock lock(mutex);
40  queue.push(f);
41  condition.notify_one();
42  }
43 
44 private:
45  void run() {
46  while(true){
47  boost::function<void()> f;
48  {
49  boost::mutex::scoped_lock lock(mutex);
50 
51  while (queue.empty() && !isDestroying){
52  condition.wait(lock);
53  }
54  if(!queue.empty()){
55  f = queue.front();
56  queue.pop();
57  }
58  }
59  if(f){
60  f();
61  } else {
62  break;
63  }
64  }
65  }
66 };
67 }
68 
69 #endif
ThreadPool(int size=1)
Definition: ThreadPool.h:21
~ThreadPool()
Definition: ThreadPool.h:28
Definition: ThreadPool.h:11
Defines the minimum processing for performing pasing file for STL.
Definition: AbstractSceneLoader.h:9
void start(boost::function< void()> f)
Definition: ThreadPool.h:38