swmutex.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /************************************************************************
  2. * AUTHOR: NiuJiuRu
  3. * FILENAME: swmutex.c
  4. * DESCRIPTION: 互斥量, 也称独占锁
  5. * NOTE: 主要用于多线程同步访问全局共享资源
  6. * HISTORY:
  7. * 1, [2010-12-17] created by NiuJiuRu
  8. ***********************************************************************/
  9. #include "swapi.h"
  10. #include "swmem.h"
  11. #include "swmutex.h"
  12. /* 创建互斥量 */
  13. void *sw_mutex_create()
  14. {
  15. pthread_mutex_t *mt = NULL;
  16. pthread_mutexattr_t attr;
  17. mt = (pthread_mutex_t *)sw_heap_malloc(sizeof(pthread_mutex_t));
  18. if(mt)
  19. {
  20. memset(mt, 0, sizeof(pthread_mutex_t));
  21. pthread_mutexattr_init(&attr);
  22. if(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP) == 0) pthread_mutex_init(mt, &attr); // 检错锁
  23. else{ sw_heap_free(mt); mt = NULL; }
  24. pthread_mutexattr_destroy(&attr);
  25. }
  26. return mt;
  27. }
  28. /* 销毁互斥量 */
  29. void sw_mutex_destroy(void *hMutex)
  30. {
  31. pthread_mutex_t *mt = (pthread_mutex_t *)hMutex;
  32. pthread_mutex_destroy(mt);
  33. sw_heap_free(mt);
  34. }
  35. /* 互斥量上锁(超时设置的时间单位为: 毫秒, 并且当timeout = -1时表示无限等待) */
  36. int sw_mutex_lock(void *hMutex, int timeout)
  37. {
  38. pthread_mutex_t *mt = (pthread_mutex_t *)hMutex;
  39. struct timespec ts = { 0 };
  40. if(timeout < 0)
  41. {
  42. return pthread_mutex_lock(mt);
  43. }
  44. else
  45. {
  46. ts.tv_sec = time(NULL) + timeout/1000;
  47. ts.tv_nsec = (timeout%1000)*1000;
  48. if(pthread_mutex_timedlock(mt, &ts) != 0) return -1;
  49. }
  50. return 0;
  51. }
  52. /* 互斥量解锁 */
  53. void sw_mutex_unlock(void *hMutex)
  54. {
  55. pthread_mutex_t *mt = (pthread_mutex_t *)hMutex;
  56. if(mt) pthread_mutex_unlock(mt);
  57. }