Open Lighting Architecture  0.9.6
 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 std::ostream& operator<<(std::ostream &stream,
38  const ptw32_handle_t &handle) {
39  stream << handle.p;
40  return stream;
41 }
42 #endif
43 
44 namespace ola {
45 namespace thread {
46 
47 typedef pthread_t ThreadId;
48 
52 class Thread {
53  public:
60  struct Options {
61  public:
65  std::string name;
66 
73  int policy;
74 
80  int priority;
81 
89 
94  explicit Options(const std::string &name = "");
95  };
96 
101  explicit Thread(const Options &options = Options());
102 
106  virtual ~Thread() {}
107 
115  virtual bool Start();
116 
124  virtual bool FastStart();
125 
131  virtual bool Join(void *ptr = NULL);
132 
140  bool IsRunning();
141 
146  ThreadId Id() const { return m_thread_id; }
147 
155  std::string Name() const { return m_options.name; }
156 
161  void* _InternalRun();
162 
167  static inline ThreadId Self() { return pthread_self(); }
168 
169  protected:
176  virtual void *Run() = 0;
177 
178  private:
179  pthread_t m_thread_id;
180  bool m_running;
181  Options m_options;
182  Mutex m_mutex; // protects m_running
183  ConditionVariable m_condition; // use to wait for the thread to start
184 
185  DISALLOW_COPY_AND_ASSIGN(Thread);
186 };
187 } // namespace thread
188 } // namespace ola
189 #endif // INCLUDE_OLA_THREAD_THREAD_H_