hmutex.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #ifndef HW_MUTEX_H_
  2. #define HW_MUTEX_H_
  3. #include "hplatform.h"
  4. #ifdef OS_WIN
  5. #define hmutex_t CRITICAL_SECTION
  6. #define hmutex_init InitializeCriticalSection
  7. #define hmutex_destroy DeleteCriticalSection
  8. #define hmutex_lock EnterCriticalSection
  9. #define hmutex_unlock LeaveCriticalSection
  10. #define honce_t INIT_ONCE
  11. #define HONCE_INIT INIT_ONCE_STATIC_INIT
  12. typedef void (WINAPI *honce_fn)();
  13. static inline BOOL WINAPI s_once_func(INIT_ONCE* once, PVOID arg, PVOID* _) {
  14. honce_fn fn = (honce_fn)arg;
  15. fn();
  16. return TRUE;
  17. }
  18. static inline void honce(INIT_ONCE* once, honce_fn fn) {
  19. PVOID dummy = NULL;
  20. InitOnceExecuteOnce(once, s_once_func, (PVOID)fn, &dummy);
  21. }
  22. #else
  23. #define hmutex_t pthread_mutex_t
  24. #define hmutex_init(mutex) pthread_mutex_init(mutex, NULL)
  25. #define hmutex_destroy pthread_mutex_destroy
  26. #define hmutex_lock pthread_mutex_lock
  27. #define hmutex_unlock pthread_mutex_unlock
  28. #define honce_t pthread_once_t
  29. #define HONCE_INIT PTHREAD_ONCE_INIT
  30. #define honce pthread_once
  31. #endif
  32. #ifdef __cplusplus
  33. #include <mutex>
  34. #ifdef _MSC_VER
  35. class RWLock {
  36. public:
  37. RWLock() { InitializeSRWLock(&_rwlock); }
  38. ~RWLock() { }
  39. void rdlock() { AcquireSRWLockShared(&_rwlock); }
  40. void rdunlock() { ReleaseSRWLockShared(&_rwlock); }
  41. void wrlock() { AcquireSRWLockExclusive(&_rwlock); }
  42. void wrunlock() { ReleaseSRWLockExclusive(&_rwlock); }
  43. private:
  44. SRWLOCK _rwlock;
  45. };
  46. #else
  47. class RWLock {
  48. public:
  49. RWLock() { pthread_rwlock_init(&_rwlock, NULL); }
  50. ~RWLock() { pthread_rwlock_destroy(&_rwlock); }
  51. void rdlock() { pthread_rwlock_rdlock(&_rwlock); }
  52. void rdunlock() { pthread_rwlock_unlock(&_rwlock); }
  53. void wrlock() { pthread_rwlock_wrlock(&_rwlock); }
  54. void wrunlock() { pthread_rwlock_unlock(&_rwlock); }
  55. private:
  56. pthread_rwlock_t _rwlock;
  57. };
  58. #endif
  59. #endif
  60. #endif // HW_MUTEX_H_