关键词搜索

源码搜索 ×
×

tars源码分析之12

发布2022-07-10浏览624次

详情内容

读写锁终于来了,一起来看看实现吧,是很典型的:

  1. #include "util/tc_thread_rwlock.h"
  2. #include <string.h>
  3. #include <iostream>
  4. #include <cassert>
  5. namespace tars
  6. {
  7. TC_ThreadRWLocker::TC_ThreadRWLocker()
  8. {
  9. int ret = ::pthread_rwlock_init(&m_sect, NULL);
  10. assert(ret == 0);
  11. if(ret != 0)
  12. {
  13. throw TC_ThreadRW_Exception("[TC_ThreadRWLocker::TC_ThreadRWLocker] pthread_rwlock_init error", ret);
  14. }
  15. }
  16. TC_ThreadRWLocker::~TC_ThreadRWLocker()
  17. {
  18. int ret = ::pthread_rwlock_destroy(&m_sect);
  19. if(ret != 0)
  20. {
  21. cerr<<"[TC_ThreadRWLocker::~TC_ThreadRWLocker] pthread_rwlock_destroy error:"<<string(strerror(ret))<<endl;;
  22. }
  23. }
  24. void TC_ThreadRWLocker::ReadLock() const
  25. {
  26. int ret = ::pthread_rwlock_rdlock(&m_sect);
  27. if(ret != 0)
  28. {
  29. if(ret == EDEADLK)
  30. {
  31. throw TC_ThreadRW_Exception("[TC_ThreadRWLocker::ReadLock] pthread_rwlock_rdlock dead lock error", ret);
  32. }
  33. else
  34. {
  35. throw TC_ThreadRW_Exception("[TC_ThreadRWLocker::ReadLock] pthread_rwlock_rdlock error", ret);
  36. }
  37. }
  38. }
  39. void TC_ThreadRWLocker::WriteLock() const
  40. {
  41. int ret = ::pthread_rwlock_wrlock(&m_sect);
  42. if(ret != 0)
  43. {
  44. if(ret == EDEADLK)
  45. {
  46. throw TC_ThreadRW_Exception("[TC_ThreadRWLocker::WriteLock] pthread_rwlock_wrlock dead lock error", ret);
  47. }
  48. else
  49. {
  50. throw TC_ThreadRW_Exception("[TC_ThreadRWLocker::WriteLock] pthread_rwlock_wrlock error", ret);
  51. }
  52. }
  53. }
  54. void TC_ThreadRWLocker::TryReadLock() const
  55. {
  56. int ret = ::pthread_rwlock_tryrdlock(&m_sect);
  57. if(ret != 0)
  58. {
  59. if(ret == EDEADLK)
  60. {
  61. throw TC_ThreadRW_Exception("[TC_ThreadRWLocker::TryReadLock] pthread_rwlock_tryrdlock dead lock error", ret);
  62. }
  63. else
  64. {
  65. throw TC_ThreadRW_Exception("[TC_ThreadRWLocker::TryReadLock] pthread_rwlock_tryrdlock error", ret);
  66. }
  67. }
  68. }
  69. void TC_ThreadRWLocker::TryWriteLock() const
  70. {
  71. int ret = ::pthread_rwlock_trywrlock(&m_sect);
  72. if(ret != 0)
  73. {
  74. if(ret == EDEADLK)
  75. {
  76. throw TC_ThreadRW_Exception("[TC_ThreadRWLocker::TryWriteLock] pthread_rwlock_trywrlock dead lock error", ret);
  77. }
  78. else
  79. {
  80. throw TC_ThreadRW_Exception("[TC_ThreadRWLocker::TryWriteLock] pthread_rwlock_trywrlock error", ret);
  81. }
  82. }
  83. }
  84. void TC_ThreadRWLocker::Unlock() const
  85. {
  86. int ret = ::pthread_rwlock_unlock(&m_sect);
  87. if(ret != 0)
  88. {
  89. throw TC_ThreadRW_Exception("[TC_ThreadRWLocker::Unlock] pthread_rwlock_unlock error", ret);
  90. }
  91. }
  92. }

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载