Open Lighting Architecture  0.9.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
ThreadPool.h
1 /*
2  * This library is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU Lesser General Public
4  * License as published by the Free Software Foundation; either
5  * version 2.1 of the License, or (at your option) any later version.
6  *
7  * This library is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10  * Lesser General Public License for more details.
11  *
12  * You should have received a copy of the GNU Lesser General Public
13  * License along with this library; if not, write to the Free Software
14  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
15  *
16  * ThreadPool.h
17  * An executor which farms work out to a bunch of threads.
18  * Copyright (C) 2011 Simon Newton
19  */
20 
21 #ifndef INCLUDE_OLA_THREAD_THREADPOOL_H_
22 #define INCLUDE_OLA_THREAD_THREADPOOL_H_
23 
24 #include <ola/Callback.h>
25 #include <ola/base/Macro.h>
26 #include <ola/thread/ConsumerThread.h>
27 #include <ola/thread/Thread.h>
28 #include <queue>
29 #include <vector>
30 
31 namespace ola {
32 namespace thread {
33 
34 class ThreadPool {
35  public :
37 
38  explicit ThreadPool(unsigned int thread_count)
39  : m_thread_count(thread_count),
40  m_shutdown(false) {
41  }
42  ~ThreadPool();
43  bool Init();
44  void JoinAll();
45  void Execute(Action action);
46 
47  private:
48  std::queue<Action> m_callback_queue;
49  unsigned int m_thread_count;
50  bool m_shutdown;
51  Mutex m_mutex;
52  ConditionVariable m_condition_var;
53  std::vector<ConsumerThread*> m_threads;
54 
55  void JoinAllThreads();
56 
57  DISALLOW_COPY_AND_ASSIGN(ThreadPool);
58 };
59 } // namespace thread
60 } // namespace ola
61 #endif // INCLUDE_OLA_THREAD_THREADPOOL_H_