Open Lighting Architecture  0.9.5
 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 #if defined(_WIN32) && defined(__GNUC__)
37 inline bool operator==(const ptw32_handle_t &left,
38  const ptw32_handle_t &right) {
39  return (left.p == right.p) && (left.x == right.x);
40 }
41 
42 inline std::ostream& operator<<(std::ostream &stream,
43  const ptw32_handle_t &handle) {
44  stream << handle.p;
45  return stream;
46 }
47 #endif
48 
49 namespace ola {
50 namespace thread {
51 
52 typedef pthread_t ThreadId;
53 
57 class Thread {
58  public:
65  struct Options {
66  public:
70  std::string name;
71 
78  int policy;
79 
85  int priority;
86 
94 
99  explicit Options(const std::string &name = "");
100  };
101 
106  explicit Thread(const Options &options = Options());
107 
111  virtual ~Thread() {}
112 
120  virtual bool Start();
121 
129  virtual bool FastStart();
130 
136  virtual bool Join(void *ptr = NULL);
137 
145  bool IsRunning();
146 
151  ThreadId Id() const { return m_thread_id; }
152 
160  std::string Name() const { return m_options.name; }
161 
166  void* _InternalRun();
167 
172  static inline ThreadId Self() { return pthread_self(); }
173 
174  protected:
181  virtual void *Run() = 0;
182 
183  private:
184  pthread_t m_thread_id;
185  bool m_running;
186  Options m_options;
187  Mutex m_mutex; // protects m_running
188  ConditionVariable m_condition; // use to wait for the thread to start
189 
190  DISALLOW_COPY_AND_ASSIGN(Thread);
191 };
192 } // namespace thread
193 } // namespace ola
194 #endif // INCLUDE_OLA_THREAD_THREAD_H_