Thread.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #ifndef THREAD_H_
  2. #define THREAD_H_
  3. namespace gameplay
  4. {
  5. #ifdef WIN32
  6. #include <Windows.h>
  7. typedef HANDLE THREAD_HANDLE;
  8. struct WindowsThreadData
  9. {
  10. int(*threadFunction)(void*);
  11. void* arg;
  12. };
  13. DWORD WINAPI WindowsThreadProc(LPVOID lpParam)
  14. {
  15. WindowsThreadData* data = (WindowsThreadData*)lpParam;
  16. int(*threadFunction)(void*) = data->threadFunction;
  17. void* arg = data->arg;
  18. delete data;
  19. data = NULL;
  20. return threadFunction(arg);
  21. }
  22. static bool createThread(THREAD_HANDLE* handle, int(*threadFunction)(void*), void* arg)
  23. {
  24. WindowsThreadData* data = new WindowsThreadData();
  25. data->threadFunction = threadFunction;
  26. data->arg = arg;
  27. *handle = CreateThread(NULL, 0, &WindowsThreadProc, data, 0, NULL);
  28. return (*handle != NULL);
  29. }
  30. static void waitForThreads(int count, THREAD_HANDLE* threads)
  31. {
  32. WaitForMultipleObjects(count, threads, TRUE, INFINITE);
  33. }
  34. static void closeThread(THREAD_HANDLE thread)
  35. {
  36. CloseHandle(thread);
  37. }
  38. #else
  39. #include <pthread.h>
  40. typedef pthread_t THREAD_HANDLE;
  41. struct PThreadData
  42. {
  43. int(*threadFunction)(void*);
  44. void* arg;
  45. };
  46. void* PThreadProc(void* threadData)
  47. {
  48. PThreadData* data = (PThreadData*)threadData;
  49. int(*threadFunction)(void*) = data->threadFunction;
  50. void* arg = data->arg;
  51. delete data;
  52. data = NULL;
  53. int retVal = threadFunction(arg);
  54. pthread_exit((void*)retVal);
  55. }
  56. static bool createThread(THREAD_HANDLE* handle, int(*threadFunction)(void*), void* arg)
  57. {
  58. PThreadData* data = new PThreadData();
  59. data->threadFunction = threadFunction;
  60. data->arg = arg;
  61. return pthread_create(handle, NULL, &PThreadProc, data) == 0;
  62. }
  63. static void waitForThreads(int count, THREAD_HANDLE* threads)
  64. {
  65. // Call join on all threads to wait for them to terminate.
  66. // This also frees any resources allocated by the threads,
  67. // essentially cleaning them up.
  68. for (int i = 0; i < count; ++i)
  69. {
  70. pthread_join(threads[i], NULL);
  71. }
  72. }
  73. static void closeThread(THREAD_HANDLE thread)
  74. {
  75. // nothing to do... waitForThreads (which calls join) cleans up
  76. }
  77. #endif
  78. }
  79. #endif