mutex.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #ifndef _LIBLOCKDEP_MUTEX_H
  2. #define _LIBLOCKDEP_MUTEX_H
  3. #include <pthread.h>
  4. #include "common.h"
  5. struct liblockdep_pthread_mutex {
  6. pthread_mutex_t mutex;
  7. struct lockdep_map dep_map;
  8. };
  9. typedef struct liblockdep_pthread_mutex liblockdep_pthread_mutex_t;
  10. #define LIBLOCKDEP_PTHREAD_MUTEX_INITIALIZER(mtx) \
  11. (const struct liblockdep_pthread_mutex) { \
  12. .mutex = PTHREAD_MUTEX_INITIALIZER, \
  13. .dep_map = STATIC_LOCKDEP_MAP_INIT(#mtx, &((&(mtx))->dep_map)), \
  14. }
  15. static inline int __mutex_init(liblockdep_pthread_mutex_t *lock,
  16. const char *name,
  17. struct lock_class_key *key,
  18. const pthread_mutexattr_t *__mutexattr)
  19. {
  20. lockdep_init_map(&lock->dep_map, name, key, 0);
  21. return pthread_mutex_init(&lock->mutex, __mutexattr);
  22. }
  23. #define liblockdep_pthread_mutex_init(mutex, mutexattr) \
  24. ({ \
  25. static struct lock_class_key __key; \
  26. \
  27. __mutex_init((mutex), #mutex, &__key, (mutexattr)); \
  28. })
  29. static inline int liblockdep_pthread_mutex_lock(liblockdep_pthread_mutex_t *lock)
  30. {
  31. lock_acquire(&lock->dep_map, 0, 0, 0, 1, NULL, (unsigned long)_RET_IP_);
  32. return pthread_mutex_lock(&lock->mutex);
  33. }
  34. static inline int liblockdep_pthread_mutex_unlock(liblockdep_pthread_mutex_t *lock)
  35. {
  36. lock_release(&lock->dep_map, 0, (unsigned long)_RET_IP_);
  37. return pthread_mutex_unlock(&lock->mutex);
  38. }
  39. static inline int liblockdep_pthread_mutex_trylock(liblockdep_pthread_mutex_t *lock)
  40. {
  41. lock_acquire(&lock->dep_map, 0, 1, 0, 1, NULL, (unsigned long)_RET_IP_);
  42. return pthread_mutex_trylock(&lock->mutex) == 0 ? 1 : 0;
  43. }
  44. static inline int liblockdep_pthread_mutex_destroy(liblockdep_pthread_mutex_t *lock)
  45. {
  46. return pthread_mutex_destroy(&lock->mutex);
  47. }
  48. #ifdef __USE_LIBLOCKDEP
  49. #define pthread_mutex_t liblockdep_pthread_mutex_t
  50. #define pthread_mutex_init liblockdep_pthread_mutex_init
  51. #define pthread_mutex_lock liblockdep_pthread_mutex_lock
  52. #define pthread_mutex_unlock liblockdep_pthread_mutex_unlock
  53. #define pthread_mutex_trylock liblockdep_pthread_mutex_trylock
  54. #define pthread_mutex_destroy liblockdep_pthread_mutex_destroy
  55. #endif
  56. #endif