TYThread.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include "TYThread.hpp"
  2. #ifdef _WIN32
  3. #include <windows.h>
  4. class TYThreadImpl
  5. {
  6. public:
  7. TYThreadImpl() : _thread(NULL) {}
  8. int create(TYThread::Callback_t cb, void* arg) {
  9. DWORD dwThreadId = 0;
  10. _thread = CreateThread(
  11. NULL, // default security attributes
  12. 0, // use default stack size
  13. (LPTHREAD_START_ROUTINE)cb, // thread function name
  14. arg, // argument to thread function
  15. 0, // use default creation flags
  16. &dwThreadId); // returns the thread identifier
  17. return 0;
  18. }
  19. int destroy() {
  20. // TerminateThread(_thread, 0);
  21. switch (WaitForSingleObject(_thread, INFINITE))
  22. {
  23. case WAIT_OBJECT_0:
  24. if (CloseHandle(_thread)) {
  25. _thread = 0;
  26. return 0;
  27. }
  28. else {
  29. return -1;
  30. }
  31. default:
  32. return -2;
  33. }
  34. }
  35. private:
  36. HANDLE _thread;
  37. };
  38. #else // _WIN32
  39. #include <pthread.h>
  40. class TYThreadImpl
  41. {
  42. public:
  43. TYThreadImpl() {}
  44. int create(TYThread::Callback_t cb, void* arg) {
  45. int ret = pthread_create(&_thread, NULL, cb, arg);
  46. return ret;
  47. }
  48. int destroy() {
  49. pthread_join(_thread, NULL);
  50. return 0;
  51. }
  52. private:
  53. pthread_t _thread;
  54. };
  55. #endif // _WIN32
  56. ////////////////////////////////////////////////////////////////////////////
  57. TYThread::TYThread()
  58. {
  59. impl = new TYThreadImpl();
  60. }
  61. TYThread::~TYThread()
  62. {
  63. delete impl;
  64. impl = NULL;
  65. }
  66. int TYThread::create(Callback_t cb, void* arg)
  67. {
  68. return impl->create(cb, arg);
  69. }
  70. int TYThread::destroy()
  71. {
  72. return impl->destroy();
  73. }