ThreadPosix.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. #include <anki/util/Thread.h>
  6. #include <anki/util/Logger.h>
  7. namespace anki
  8. {
  9. void Thread::start(void* userData, ThreadCallback callback, I32 pinToCore)
  10. {
  11. ANKI_ASSERT(!m_started);
  12. ANKI_ASSERT(callback != nullptr);
  13. m_callback = callback;
  14. m_userData = userData;
  15. #if ANKI_EXTRA_CHECKS
  16. m_started = true;
  17. #endif
  18. pthread_attr_t attr;
  19. cpu_set_t cpus;
  20. pthread_attr_init(&attr);
  21. if(pinToCore >= 0)
  22. {
  23. CPU_ZERO(&cpus);
  24. CPU_SET(pinToCore, &cpus);
  25. pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpus);
  26. }
  27. auto pthreadCallback = [](void* ud) -> void* {
  28. ANKI_ASSERT(ud != nullptr);
  29. Thread* thread = static_cast<Thread*>(ud);
  30. // Set thread name
  31. if(thread->m_name[0] != '\0')
  32. {
  33. pthread_setname_np(pthread_self(), &thread->m_name[0]);
  34. }
  35. // Call the callback
  36. ThreadCallbackInfo info;
  37. info.m_userData = thread->m_userData;
  38. info.m_threadName = &thread->m_name[0];
  39. const Error err = thread->m_callback(info);
  40. return numberToPtr<void*>(err._getCode());
  41. };
  42. if(ANKI_UNLIKELY(pthread_create(&m_handle, &attr, pthreadCallback, this)))
  43. {
  44. ANKI_UTIL_LOGF("pthread_create() failed");
  45. }
  46. pthread_attr_destroy(&attr);
  47. }
  48. Error Thread::join()
  49. {
  50. void* out;
  51. if(ANKI_UNLIKELY(pthread_join(m_handle, &out)))
  52. {
  53. ANKI_UTIL_LOGF("pthread_join() failed");
  54. }
  55. #if ANKI_EXTRA_CHECKS
  56. m_started = false;
  57. #endif
  58. // Set return error code
  59. return Error(I32(ptrToNumber(out)));
  60. }
  61. } // end namespace anki