My Project
Thread.hpp
1 #pragma once
2 
3 // Use Win or Posix
4 #ifdef WIN32
5 #include <windows.h>
6 #else
7 #ifndef POSIX
8 #warning POSIX will be used (but you did not define it)
9 #endif
10 #include <pthread.h>
11 #include <signal.h>
12 #endif
13 
14 namespace ParaEngine
15 {
27  class Thread{
28  private:
33  void operator=(const Thread &){}
38  Thread(const Thread &){}
39 
40 #ifdef WIN32
41  HANDLE _handle;
42 #else
43  pthread_t _thread;
44 #endif
45 
46  bool _isRunning;
52 #ifdef WIN32
53  static DWORD WINAPI Starter(LPVOID in_thread){
54 #else
55  static void* Starter(void* in_thread){
56 #endif
57  Thread * thread = static_cast< Thread * >(in_thread);
58  thread->_isRunning = true;
59  thread->run();
60  thread->_isRunning = false;
61 
62  return 0x00;
63  }
64 
65  public:
69  Thread(){
70 #ifdef WIN32
71  _handle = 0x00;
72 #else
73 #endif
74  _isRunning = false;
75  }
79  virtual ~Thread(){
80  if(_isRunning)
81  {
82  // if we destroy the thread until it has finished
83  // there is a problem in your implementation algorithm
84  // So we wait before destroying the thread!
85  wait();
86  }
87 #ifdef WIN32
88  if(_handle !=0)
89  CloseHandle (_handle);
90 #else
91 #endif
92  }
93 
98  bool start(){
99  if(_isRunning) return false;
100 #ifdef WIN32
101  _handle = CreateThread( 0x00, 0x00,Thread::Starter, static_cast< void* >(this), 0x00, 0x00);
102  return _handle != NULL;
103 #else
104  return pthread_create(&_thread, NULL, Thread::Starter, static_cast< void* >(this)) == 0;
105 #endif
106  }
107 
112  bool isRunning() const{
113  return _isRunning;
114  }
115 
120  bool wait() const{
121  if(!_isRunning) return false;
122 #ifdef WIN32
123  return WaitForSingleObject(_handle,INFINITE) == 0x00000000L;
124 #else
125  return pthread_join(_thread, NULL) == 0;
126 #endif
127 
128  }
129 
134  virtual void run() = 0;
135 
139  bool kill(){
140  if(!_isRunning) return false;
141 
142  _isRunning = false;
143 #ifdef WIN32
144  bool success = TerminateThread(_handle,1) && CloseHandle(_handle);
145  _handle = 0x00;
146  return success;
147 #else
148  return pthread_kill( _thread, SIGKILL) == 0;
149 #endif
150  }
151 
152  };
153 }
154 
virtual void run()=0
the function is called when thread is starting You must implement this methode!
bool wait() const
Wait the end of a thread.
Definition: Thread.hpp:120
different physics engine has different winding order.
Definition: EventBinding.h:32
bool isRunning() const
Fast look up to know if a thread is running.
Definition: Thread.hpp:112
bool start()
start the thread
Definition: Thread.hpp:98
virtual ~Thread()
Destructor, Warning, it waits the end of the current thread.
Definition: Thread.hpp:79
Thread()
Constructor.
Definition: Thread.hpp:69
cross platform thread.
Definition: Thread.hpp:27