YDLIDAR X2 SDK  V1.4.1
thread.h
1 #pragma once
2 #include "v8stdint.h"
3 
4 #ifdef _WIN32
5 #include <conio.h>
6 #include <windows.h>
7 #include <io.h>
8 #include <process.h>
9 #else
10 #include <pthread.h>
11 #include <assert.h>
12 #endif
13 
14 #define UNUSED(x) (void)x
15 
16 #if defined(__ANDROID__)
17 #define pthread_cancel(x) 0
18 #endif
19 
20 #define CLASS_THREAD(c , x ) Thread::ThreadCreateObjectFunctor<c, &c::x>(this)
21 
22 class Thread
23 {
24 public:
25 
26  template <class CLASS, int (CLASS::*PROC)(void)> static Thread ThreadCreateObjectFunctor(CLASS * pthis){
27  return createThread(createThreadAux<CLASS,PROC>, pthis);
28  }
29 
30  template <class CLASS, int (CLASS::*PROC)(void) > static _size_t THREAD_PROC createThreadAux(void * param){
31  return (static_cast<CLASS *>(param)->*PROC)();
32  }
33 
34  static Thread createThread(thread_proc_t proc, void * param = NULL ){
35  Thread thread_(proc, param);
36 #if defined(_WIN32)
37  thread_._handle = (_size_t)( _beginthreadex(NULL, 0, (unsigned int (__stdcall * )( void * ))proc, param, 0, NULL));
38 #else
39  assert( sizeof(thread_._handle) >= sizeof(pthread_t));
40 
41  pthread_create((pthread_t *)&thread_._handle, NULL, (void * (*)(void *))proc, param);
42 #endif
43  return thread_;
44  }
45 
46 public:
47  explicit Thread(): _param(NULL),_func(NULL),_handle(0){}
48  virtual ~Thread(){}
49  _size_t getHandle(){
50  return _handle;
51  }
52  int terminate(){
53 #if defined(_WIN32)
54  if (!this->_handle){
55  return 0;
56  }
57  if (TerminateThread( reinterpret_cast<HANDLE>(this->_handle), -1)){
58  CloseHandle(reinterpret_cast<HANDLE>(this->_handle));
59  this->_handle = NULL;
60  return 0;
61  }else{
62  return -2;
63  }
64 
65 #else
66  if (!this->_handle) return 0;
67 
68  return pthread_cancel((pthread_t)this->_handle);
69 #endif
70  }
71  void *getParam() {
72  return _param;
73  }
74  int join(unsigned long timeout = -1){
75  if (!this->_handle){
76  return 0;
77  }
78 #if defined(_WIN32)
79  switch ( WaitForSingleObject(reinterpret_cast<HANDLE>(this->_handle), timeout)){
80  case WAIT_OBJECT_0:
81  CloseHandle(reinterpret_cast<HANDLE>(this->_handle));
82  this->_handle = NULL;
83  return 0;
84  case WAIT_ABANDONED:
85  return -2;
86  case WAIT_TIMEOUT:
87  return -1;
88  }
89 #else
90  UNUSED(timeout);
91  pthread_join((pthread_t)(this->_handle), NULL);
92 #endif
93  return 0;
94  }
95 
96  bool operator== ( const Thread & right) {
97  return this->_handle == right._handle;
98  }
99 protected:
100  explicit Thread( thread_proc_t proc, void * param ):_param(param),_func(proc), _handle(0){}
101  void * _param;
102  thread_proc_t _func;
103  _size_t _handle;
104 };
105 
Definition: thread.h:22