lock.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include "log.h"
  5. #include "lock.h"
  6. #define MALLOC malloc
  7. #define FREE free
  8. //static global lock
  9. static pthread_mutex_t *mutex_pool[LOCK_ID_MAX]={0};
  10. int lock_s_init(void)
  11. {
  12. int i,r;
  13. pthread_mutex_t *m=NULL;
  14. for(i=0; i<LOCK_ID_MAX; i++) {
  15. m = MALLOC(sizeof(pthread_mutex_t));
  16. if(m) {
  17. r = pthread_mutex_init(m, NULL);
  18. if(r) {
  19. LOGE("lock_s_init %d failed\n", i);
  20. FREE(m); m = NULL;
  21. }
  22. mutex_pool[i] = m;
  23. }
  24. }
  25. return 0;
  26. }
  27. int lock_s_deinit(void)
  28. {
  29. int i,r;
  30. for(i=0; i<LOCK_ID_MAX; i++) {
  31. if(mutex_pool[i]) {
  32. r = pthread_mutex_destroy(mutex_pool[i]);
  33. if(r) {
  34. LOGE("lock_s_deinit %d failed\n", i);
  35. continue;
  36. }
  37. mutex_pool[i] = NULL;
  38. }
  39. }
  40. return 0;
  41. }
  42. int lock_s_hold(int id)
  43. {
  44. if(id<0 || id>=LOCK_ID_MAX || !mutex_pool[id]) {
  45. return -1;
  46. }
  47. return pthread_mutex_lock(mutex_pool[id]);
  48. }
  49. int lock_s_release(int id)
  50. {
  51. if(id<0 || id>=LOCK_ID_MAX || !mutex_pool[id]) {
  52. return -1;
  53. }
  54. return pthread_mutex_unlock(mutex_pool[id]);
  55. }
  56. ///////////////////////////////////////////////////////
  57. lock_t lock_d_init(void)
  58. {
  59. int r;
  60. pthread_mutex_t *m=MALLOC(sizeof(pthread_mutex_t));
  61. if(!m) {
  62. return 0;
  63. }
  64. r = pthread_mutex_init(m, NULL);
  65. if(r) {
  66. LOGE("pthread_mutex_create failed\n");
  67. FREE(m); return 0;
  68. }
  69. return (lock_t)m;
  70. }
  71. int lock_d_deinit(lock_t h)
  72. {
  73. int r;
  74. if(!h) {
  75. return -1;
  76. }
  77. r = pthread_mutex_destroy((pthread_mutex_t*)h);
  78. FREE((void*)h);
  79. return r;
  80. }
  81. int lock_d_hold(lock_t h)
  82. {
  83. if(!h) {
  84. return -1;
  85. }
  86. return pthread_mutex_lock((pthread_mutex_t*)h);
  87. }
  88. int lock_d_release(lock_t h)
  89. {
  90. if(!h) {
  91. return -1;
  92. }
  93. return pthread_mutex_unlock((pthread_mutex_t*)h);
  94. }