ThreadWindows.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright (C) 2009-2020, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. // Add support for condition variables
  6. #define _WIN32_WINNT _WIN32_WINNT_VISTA
  7. #include <anki/util/Thread.h>
  8. #include <anki/util/Logger.h>
  9. namespace anki
  10. {
  11. DWORD ANKI_WINAPI Thread::threadCallback(LPVOID ud)
  12. {
  13. ANKI_ASSERT(ud != nullptr);
  14. Thread* thread = reinterpret_cast<Thread*>(ud);
  15. // Set thread name
  16. if(thread->m_name[0] != '\0')
  17. {
  18. // TODO
  19. }
  20. // Call the callback
  21. ThreadCallbackInfo info;
  22. info.m_userData = thread->m_userData;
  23. info.m_threadName = &thread->m_name[0];
  24. thread->m_returnCode = thread->m_callback(info);
  25. return thread->m_returnCode._getCode();
  26. }
  27. void Thread::start(void* userData, ThreadCallback callback, I32 pinToCore)
  28. {
  29. ANKI_ASSERT(!m_started);
  30. ANKI_ASSERT(callback != nullptr);
  31. m_callback = callback;
  32. m_userData = userData;
  33. #if ANKI_EXTRA_CHECKS
  34. m_started = true;
  35. #endif
  36. m_returnCode = Error::NONE;
  37. m_handle = CreateThread(nullptr, 0, threadCallback, this, 0, nullptr);
  38. if(m_handle == nullptr)
  39. {
  40. ANKI_UTIL_LOGF("CreateThread() failed");
  41. }
  42. if(pinToCore >= 0)
  43. {
  44. if(SetThreadAffinityMask(m_handle, DWORD_PTR(1) << DWORD_PTR(pinToCore)) == 0)
  45. {
  46. ANKI_UTIL_LOGF("SetThreadAffinityMask() failed");
  47. }
  48. }
  49. }
  50. Error Thread::join()
  51. {
  52. ANKI_ASSERT(m_started);
  53. // Wait thread
  54. WaitForSingleObject(m_handle, INFINITE);
  55. // Delete handle
  56. const BOOL ok = CloseHandle(m_handle);
  57. if(!ok)
  58. {
  59. ANKI_UTIL_LOGF("CloseHandle() failed");
  60. }
  61. m_handle = nullptr;
  62. #if ANKI_EXTRA_CHECKS
  63. m_started = false;
  64. #endif
  65. return m_returnCode;
  66. }
  67. } // end namespace anki