Locks.h 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. //
  2. // Copyright @ 2014 Hangzhou Topzen Ltd.
  3. // Author: Tang (tang@hztopzen.com) @ 2014-12
  4. //
  5. #ifndef __LOCKS_H
  6. #define __LOCKS_H
  7. #include "Types.h"
  8. namespace tzc {
  9. class DECLDLL Mutex {
  10. public:
  11. Mutex(TZ_BOOL bFast = false);
  12. ~Mutex();
  13. void Lock();
  14. TZ_BOOL TryLock();
  15. TZ_BOOL TryLock(const TZ_LONG mseconds);
  16. void Unlock();
  17. private:
  18. #if defined(WIN32) || defined(WINDOWS)
  19. CRITICAL_SECTION m_cs;
  20. #elif defined(LINUX)
  21. pthread_mutex_t m_mutex;
  22. #endif
  23. };
  24. class DECLDLL RWLock {
  25. public:
  26. RWLock();
  27. ~RWLock();
  28. void ReadLock();
  29. TZ_BOOL TryReadLock();
  30. void WriteLock();
  31. TZ_BOOL TryWriteLock();
  32. void Unlock();
  33. private:
  34. #if defined(WIN32) || defined(WINDOWS)
  35. typedef enum _LockState
  36. {
  37. RWLOCK_IDLE,
  38. RWLOCK_READ,
  39. RWLOCK_WRITE,
  40. RWLOCK_END
  41. }LockState;
  42. TZ_Int32 m_iState; // Lock State
  43. TZ_Int32 m_iRDLockCnt; // ReadLock Count
  44. TZ_Int32 m_iRDWaitingCnt; // ReadLock Waiting Count
  45. TZ_Int32 m_iWRWaitingCnt; // WriteLock Waiting Count
  46. HANDLE m_ev; // Event
  47. CRITICAL_SECTION m_cs; // Critical Section
  48. #elif defined(LINUX)
  49. pthread_rwlock_t m_rw;
  50. #endif
  51. };
  52. class DECLDLL ScopedLock {
  53. public:
  54. ScopedLock(Mutex & mtx) : m_mutex(mtx)
  55. {
  56. m_mutex.Lock();
  57. }
  58. ~ScopedLock()
  59. {
  60. m_mutex.Unlock();
  61. }
  62. private:
  63. Mutex & m_mutex;
  64. private:
  65. ScopedLock(const ScopedLock &);
  66. ScopedLock & operator=(const ScopedLock &);
  67. };
  68. } // namespace tzc
  69. #endif /* ----- #ifndef __LOCKS_H ----- */