sw_rwlock.c 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /************************************************************************
  2. * AUTHOR: NiuJiuRu
  3. * FILENAME: sw_rwlock.c
  4. * DESCRIPTION: 读写锁, 也称共享锁
  5. * NOTE: 主要用于多线程同步访问全局共享资源
  6. * HISTORY:
  7. * 1, [2014-01-24] created by NiuJiuRu
  8. ***********************************************************************/
  9. #include "swapi.h"
  10. #include "swmem.h"
  11. #include "sw_rwlock.h"
  12. /* 创建读写锁 */
  13. void *sw_rwlock_create()
  14. {
  15. pthread_rwlock_t *rwlock = NULL;
  16. pthread_rwlockattr_t attr;
  17. rwlock = (pthread_rwlock_t *)sw_heap_malloc(sizeof(pthread_rwlock_t));
  18. if(rwlock)
  19. {
  20. memset(rwlock, 0, sizeof(pthread_rwlock_t));
  21. pthread_rwlockattr_init(&attr);
  22. // note: "If the process-shared attribute is PTHREAD_PRO-CESS_PRIVATE, the read-write lock shall only be
  23. // operated upon by threads created within the same process as the thread that initialized the read-write lock;
  24. // if threads of differing processes attempt to operate on such a read-write lock, the behavior is undefined."
  25. if(pthread_rwlockattr_setpshared(&attr, PTHREAD_PROCESS_PRIVATE) == 0) pthread_rwlock_init(rwlock, &attr);
  26. else{ sw_heap_free(rwlock); rwlock = NULL; }
  27. pthread_rwlockattr_destroy(&attr);
  28. }
  29. return rwlock;
  30. }
  31. /* 销毁读写锁 */
  32. void sw_rwlock_destroy(void *hRWLock)
  33. {
  34. pthread_rwlock_t *rwlock = (pthread_rwlock_t *)hRWLock;
  35. pthread_rwlock_destroy(rwlock);
  36. sw_heap_free(rwlock);
  37. }
  38. /* 读写锁上锁-读(超时设置的时间单位为: 毫秒, 并且当timeout = -1时表示无限等待) */
  39. int sw_rwlock_rdlock(void *hRWLock, int timeout)
  40. {
  41. pthread_rwlock_t *rwlock = (pthread_rwlock_t *)hRWLock;
  42. struct timespec ts = { 0 };
  43. if(timeout < 0)
  44. {
  45. return pthread_rwlock_rdlock(rwlock);
  46. }
  47. else
  48. {
  49. ts.tv_sec = time(NULL) + timeout/1000;
  50. ts.tv_nsec = (timeout%1000)*1000;
  51. if(pthread_rwlock_timedrdlock(rwlock, &ts) != 0) return -1;
  52. }
  53. return 0;
  54. }
  55. /* 读写锁上锁-写(超时设置的时间单位为: 毫秒, 并且当timeout = -1时表示无限等待) */
  56. int sw_rwlock_wrlock(void *hRWLock, int timeout)
  57. {
  58. pthread_rwlock_t *rwlock = (pthread_rwlock_t *)hRWLock;
  59. struct timespec ts = { 0 };
  60. if(timeout < 0)
  61. {
  62. return pthread_rwlock_wrlock(rwlock);
  63. }
  64. else
  65. {
  66. ts.tv_sec = time(NULL) + timeout/1000;
  67. ts.tv_nsec = (timeout%1000)*1000;
  68. if(pthread_rwlock_timedwrlock(rwlock, &ts) != 0) return -1;
  69. }
  70. return 0;
  71. }
  72. /* 读写锁解锁 */
  73. void sw_rwlock_unlock(void *hRWLock)
  74. {
  75. pthread_rwlock_t *rwlock = (pthread_rwlock_t *)hRWLock;
  76. pthread_rwlock_unlock(rwlock);
  77. }