Open Lighting Architecture  0.9.2
 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 namespace ola {
35 namespace thread {
36 
37 typedef pthread_t ThreadId;
38 
42 class Thread {
43  public:
44  Thread(): m_thread_id(), m_running(false) {}
45  virtual ~Thread() {}
46 
47  virtual bool Start();
48  virtual bool FastStart();
49  virtual bool Join(void *ptr = NULL);
50  bool IsRunning();
51 
52  ThreadId Id() const { return m_thread_id; }
53 
54  // Called by pthread_create
55  void *_InternalRun();
56 
57  static inline ThreadId Self() { return pthread_self(); }
58 
59  protected:
60  // Sub classes implement this.
61  virtual void *Run() = 0;
62 
63  private:
64  pthread_t m_thread_id;
65  bool m_running;
66  Mutex m_mutex; // protects m_running
67  ConditionVariable m_condition; // use to wait for the thread to start
68 
69  DISALLOW_COPY_AND_ASSIGN(Thread);
70 };
71 } // namespace thread
72 } // namespace ola
73 #endif // INCLUDE_OLA_THREAD_THREAD_H_