Thread.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include "core/thread/Thread.hpp"
  2. #include <threads.h>
  3. #include "core/utils/Meta.hpp"
  4. #include "core/utils/Utility.hpp"
  5. Core::Thread::Thread() : thread() {
  6. }
  7. Core::Thread::Thread(Thread&& other) : thread() {
  8. swap(other);
  9. }
  10. static bool doesExist(thrd_t* t) {
  11. thrd_t zero{};
  12. return !Core::memoryCompare(&zero, t, sizeof(thrd_t));
  13. }
  14. static void reset(thrd_t* t) {
  15. Core::memorySet(t, 0, sizeof(thrd_t));
  16. }
  17. Core::Thread::~Thread() {
  18. if(doesExist(thread.as<thrd_t>())) {
  19. (void)join(nullptr);
  20. }
  21. }
  22. Core::Thread& Core::Thread::operator=(Thread&& other) {
  23. if(this != &other) {
  24. if(doesExist(thread.as<thrd_t>())) {
  25. (void)join(nullptr);
  26. }
  27. reset(thread.as<thrd_t>());
  28. swap(other);
  29. }
  30. return *this;
  31. }
  32. check_return Core::Error Core::Thread::start(Function f, void* p) {
  33. CORE_ASSERT_ALIGNED_DATA(thread, thrd_t);
  34. return thrd_create(thread.as<thrd_t>(), f, p) != thrd_success
  35. ? Error::THREAD_ERROR
  36. : Error::NONE;
  37. }
  38. check_return Core::Error Core::Thread::join(int* returnValue) {
  39. int e = thrd_join(*thread.as<thrd_t>(), returnValue);
  40. reset(thread.as<thrd_t>());
  41. return e != thrd_success ? Error::THREAD_ERROR : Error::NONE;
  42. }
  43. void Core::Thread::swap(Thread& other) {
  44. thrd_t tmp;
  45. memoryCopy(&tmp, thread.as<thrd_t>(), sizeof(thrd_t));
  46. memoryCopy(thread.as<thrd_t>(), other.thread.as<thrd_t>(), sizeof(thrd_t));
  47. memoryCopy(other.thread.as<thrd_t>(), &tmp, sizeof(thrd_t));
  48. }