Thread.cpp 1.5 KB

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