基质喷涂
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.1 KiB

3 weeks ago
  1. #include "mutex.hpp"
  2. #define TAG "zmutex"
  3. using namespace iflytop;
  4. /*******************************************************************************
  5. * zmutex *
  6. *******************************************************************************/
  7. #if 0
  8. zmutex::zmutex(const char* name) { this->name = name; }
  9. zmutex::~zmutex() { vSemaphoreDelete(recursiveMutex); }
  10. void zmutex::init() {
  11. recursiveMutex = xSemaphoreCreateRecursiveMutex();
  12. ZASSERT_INFO(recursiveMutex != NULL, "zmutex (%s) init failed", name);
  13. }
  14. bool zmutex::isInit() { return recursiveMutex != NULL; }
  15. void zmutex::lock() {
  16. // ZASSERT(recursiveMutex != NULL);
  17. ZASSERT_INFO(recursiveMutex != NULL, "zmutex (%s) not init, init it", name);
  18. xSemaphoreTakeRecursive(recursiveMutex, portMAX_DELAY);
  19. }
  20. void zmutex::unlock() { xSemaphoreGiveRecursive(recursiveMutex); }
  21. /*******************************************************************************
  22. * zlock_guard *
  23. *******************************************************************************/
  24. zlock_guard::zlock_guard(zmutex& mutex) : m_mutex(mutex) { m_mutex.lock(); }
  25. zlock_guard::~zlock_guard() { m_mutex.unlock(); }
  26. #else
  27. zmutex::zmutex(const char* name) {
  28. // 为了避免悬空指针,这里使用strdup复制字符串
  29. this->name = name? strdup(name) : nullptr;
  30. }
  31. zmutex::~zmutex() {
  32. if (recursiveMutex!= nullptr) {
  33. vQueueDelete(recursiveMutex);
  34. }
  35. if (name!= nullptr) {
  36. free((void*)name);
  37. }
  38. }
  39. void zmutex::init() {
  40. recursiveMutex = xSemaphoreCreateRecursiveMutex();
  41. ZASSERT_INFO(recursiveMutex!= NULL, "zmutex (%s) init failed", name);
  42. }
  43. bool zmutex::isInit() {
  44. return recursiveMutex!= NULL;
  45. }
  46. void zmutex::lock() {
  47. ZASSERT_INFO(recursiveMutex!= NULL, "zmutex (%s) not init, init it", name);
  48. xSemaphoreTakeRecursive(recursiveMutex, portMAX_DELAY);
  49. }
  50. void zmutex::unlock() {
  51. xSemaphoreGiveRecursive(recursiveMutex);
  52. }
  53. zlock_guard::zlock_guard(zmutex& mutex) : m_mutex(mutex) {
  54. m_mutex.lock();
  55. }
  56. zlock_guard::~zlock_guard() {
  57. m_mutex.unlock();
  58. }
  59. #endif