Mutex.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include "core/thread/Mutex.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(mtx_t* m) {
  7. memset(m, 0, sizeof(mtx_t));
  8. }
  9. Core::Mutex::Mutex() : mutex() {
  10. CORE_ASSERT_ALIGNED_DATA(mutex, mtx_t);
  11. reset(mutex.as<mtx_t>());
  12. }
  13. static bool doesExist(mtx_t* t) {
  14. mtx_t zero{};
  15. return memcmp(&zero, t, sizeof(mtx_t)) != 0;
  16. }
  17. Core::Mutex::~Mutex() {
  18. if(doesExist(mutex.as<mtx_t>())) {
  19. mtx_destroy(mutex.as<mtx_t>());
  20. }
  21. }
  22. check_return Core::Error Core::Mutex::init() {
  23. if(doesExist(mutex.as<mtx_t>())) {
  24. return ErrorCode::INVALID_STATE;
  25. }
  26. return mtx_init(mutex.as<mtx_t>(), mtx_plain) != thrd_success
  27. ? ErrorCode::MUTEX_ERROR
  28. : ErrorCode::NONE;
  29. }
  30. check_return Core::Error Core::Mutex::lock() {
  31. return mtx_lock(mutex.as<mtx_t>()) != thrd_success ? ErrorCode::MUTEX_ERROR
  32. : ErrorCode::NONE;
  33. }
  34. check_return Core::Error Core::Mutex::unlock() {
  35. return mtx_unlock(mutex.as<mtx_t>()) != thrd_success
  36. ? ErrorCode::MUTEX_ERROR
  37. : ErrorCode::NONE;
  38. }