Thread.cpp 1.2 KB

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