Open Lighting Architecture  0.9.4
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Thread.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  * Thread.h
17  * A thread object.
18  * Copyright (C) 2010 Simon Newton
19  */
20 
21 #ifndef INCLUDE_OLA_THREAD_THREAD_H_
22 #define INCLUDE_OLA_THREAD_THREAD_H_
23 
24 #ifdef _WIN32
25 // On MinGW, pthread.h pulls in Windows.h, which in turn pollutes the global
26 // namespace. We define VC_EXTRALEAN and WIN32_LEAN_AND_MEAN to reduce this.
27 #define VC_EXTRALEAN
28 #define WIN32_LEAN_AND_MEAN
29 #endif
30 #include <pthread.h>
31 #include <ola/base/Macro.h>
32 #include <ola/thread/Mutex.h>
33 
34 #include <string>
35 
36 namespace ola {
37 namespace thread {
38 
39 typedef pthread_t ThreadId;
40 
44 class Thread {
45  public:
52  struct Options {
53  public:
57  std::string name;
58 
65  int policy;
66 
72  int priority;
73 
81 
86  explicit Options(const std::string &name = "");
87  };
88 
93  explicit Thread(const Options &options = Options());
94 
98  virtual ~Thread() {}
99 
107  virtual bool Start();
108 
116  virtual bool FastStart();
117 
123  virtual bool Join(void *ptr = NULL);
124 
132  bool IsRunning();
133 
138  ThreadId Id() const { return m_thread_id; }
139 
147  std::string Name() const { return m_options.name; }
148 
153  void* _InternalRun();
154 
159  static inline ThreadId Self() { return pthread_self(); }
160 
161  protected:
168  virtual void *Run() = 0;
169 
170  private:
171  pthread_t m_thread_id;
172  bool m_running;
173  Options m_options;
174  Mutex m_mutex; // protects m_running
175  ConditionVariable m_condition; // use to wait for the thread to start
176 
177  DISALLOW_COPY_AND_ASSIGN(Thread);
178 };
179 } // namespace thread
180 } // namespace ola
181 #endif // INCLUDE_OLA_THREAD_THREAD_H_