TracyThread.hpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #ifndef __TRACYTHREAD_HPP__
  2. #define __TRACYTHREAD_HPP__
  3. #if defined _WIN32 || defined __CYGWIN__
  4. # include <windows.h>
  5. #else
  6. # include <pthread.h>
  7. #endif
  8. #ifdef TRACY_MANUAL_LIFETIME
  9. # include "tracy_rpmalloc.hpp"
  10. #endif
  11. namespace tracy
  12. {
  13. class ThreadExitHandler
  14. {
  15. public:
  16. ~ThreadExitHandler()
  17. {
  18. #ifdef TRACY_MANUAL_LIFETIME
  19. rpmalloc_thread_finalize();
  20. #endif
  21. }
  22. };
  23. #if defined _WIN32 || defined __CYGWIN__
  24. class Thread
  25. {
  26. public:
  27. Thread( void(*func)( void* ptr ), void* ptr )
  28. : m_func( func )
  29. , m_ptr( ptr )
  30. , m_hnd( CreateThread( nullptr, 0, Launch, this, 0, nullptr ) )
  31. {}
  32. ~Thread()
  33. {
  34. WaitForSingleObject( m_hnd, INFINITE );
  35. CloseHandle( m_hnd );
  36. }
  37. HANDLE Handle() const { return m_hnd; }
  38. private:
  39. static DWORD WINAPI Launch( void* ptr ) { ((Thread*)ptr)->m_func( ((Thread*)ptr)->m_ptr ); return 0; }
  40. void(*m_func)( void* ptr );
  41. void* m_ptr;
  42. HANDLE m_hnd;
  43. };
  44. #else
  45. class Thread
  46. {
  47. public:
  48. Thread( void(*func)( void* ptr ), void* ptr )
  49. : m_func( func )
  50. , m_ptr( ptr )
  51. {
  52. pthread_create( &m_thread, nullptr, Launch, this );
  53. }
  54. ~Thread()
  55. {
  56. pthread_join( m_thread, nullptr );
  57. }
  58. pthread_t Handle() const { return m_thread; }
  59. private:
  60. static void* Launch( void* ptr ) { ((Thread*)ptr)->m_func( ((Thread*)ptr)->m_ptr ); return nullptr; }
  61. void(*m_func)( void* ptr );
  62. void* m_ptr;
  63. pthread_t m_thread;
  64. };
  65. #endif
  66. }
  67. #endif