Thread.cpp 1.5 KB

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