luat_rtos_mutex_pc.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include "luat_base.h"
  2. #include "luat_rtos.h"
  3. #include "luat_malloc.h"
  4. #include "uv.h"
  5. #define LUAT_LOG_TAG "rtos.mutex"
  6. #include "luat_log.h"
  7. #ifndef LUAT_MUTEX_DEBUG
  8. #define LUAT_MUTEX_DEBUG 0
  9. #endif
  10. #if LUAT_MUTEX_DEBUG == 0
  11. #undef LLOGD
  12. #define LLOGD(...)
  13. #endif
  14. typedef struct pc_mutex
  15. {
  16. uv_mutex_t m;
  17. int lock;
  18. }pc_mutex_t;
  19. /* -----------------------------------信号量模拟互斥锁,可以在中断中unlock-------------------------------*/
  20. void *luat_mutex_create(void) {
  21. pc_mutex_t* m = luat_heap_malloc(sizeof(pc_mutex_t));
  22. if (m == NULL) {
  23. LLOGE("mutex 分配内存失败");
  24. return NULL;
  25. }
  26. memset(m, 0, sizeof(pc_mutex_t));
  27. int ret = uv_mutex_init(&m->m);
  28. if (ret) {
  29. LLOGE("mutex 初始化失败 %d", ret);
  30. luat_heap_free(m);
  31. return NULL;
  32. }
  33. return m;
  34. }
  35. LUAT_RET luat_mutex_lock(void *mutex) {
  36. if (mutex == NULL) {
  37. return -1;
  38. }
  39. pc_mutex_t* m = (pc_mutex_t*)mutex;
  40. LLOGD("mutex lock1 %p %d", m, m->lock);
  41. uv_mutex_lock(&m->m);
  42. m->lock ++;
  43. LLOGD("mutex lock2 %p %d", m, m->lock);
  44. return 0;
  45. }
  46. LUAT_RET luat_mutex_unlock(void *mutex) {
  47. if (mutex == NULL)
  48. return -1;
  49. pc_mutex_t* m = (pc_mutex_t*)mutex;
  50. LLOGD("mutex unlock1 %p %d", m, m->lock);
  51. if (m->lock == 0) {
  52. //LLOGI("该mutex未加锁,不能unlock %p", mutex);
  53. return -2;
  54. }
  55. uv_mutex_unlock(&m->m);
  56. m->lock --;
  57. LLOGD("mutex unlock2 %p %d", m, m->lock);
  58. return 0;
  59. }
  60. void luat_mutex_release(void *mutex) {
  61. if (mutex == NULL)
  62. return;
  63. pc_mutex_t* m = (pc_mutex_t*)mutex;
  64. LLOGD("mutex release %p %d", m, m->lock);
  65. if (&m->lock == 0)
  66. uv_mutex_destroy(&m->m);
  67. luat_heap_free(m);
  68. }