pthread_lock.hpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. //
  2. // pthread_lock.cpp
  3. // threadpp
  4. //
  5. // Created by Melo Yao on 1/15/15.
  6. // Copyright (c) 2015 Melo Yao. All rights reserved.
  7. //
  8. #ifndef __threadpp__pthread_lock__hpp__
  9. #define __threadpp__pthread_lock__hpp__
  10. #include "../threadpp_assert.h"
  11. #include <errno.h>
  12. #include <cstring>
  13. #include <sys/time.h>
  14. static inline void timespec_for(struct timespec* t,unsigned long millisecs) {
  15. struct timeval tv;
  16. gettimeofday(&tv, NULL);
  17. t->tv_nsec = tv.tv_usec*1000 + millisecs*1000000;
  18. t->tv_sec = tv.tv_sec + (t->tv_nsec/1000000000);
  19. t->tv_nsec = t->tv_nsec%1000000000;
  20. }
  21. namespace threadpp{
  22. inline pthread_lock::pthread_lock()
  23. {
  24. pthread_mutex_init(&_mutex, NULL);
  25. pthread_cond_init(&_cond, NULL);
  26. }
  27. inline pthread_lock::~pthread_lock()
  28. {
  29. pthread_mutex_destroy(&_mutex);
  30. pthread_cond_destroy(&_cond);
  31. }
  32. inline void pthread_lock::lock()
  33. {
  34. int code = pthread_mutex_lock(&_mutex);
  35. ASSERT(code == 0, "lock failed,error:%s",strerror(code));
  36. }
  37. inline void pthread_lock::unlock()
  38. {
  39. int code = pthread_mutex_unlock(&_mutex);
  40. ASSERT(code == 0, "unlock failed,error:%s",strerror(code));
  41. }
  42. inline void pthread_lock::wait()
  43. {
  44. int code = pthread_cond_wait(&_cond, &_mutex);
  45. ASSERT(code == 0 || code == ETIMEDOUT, "wait failed,error:%s",strerror(code));
  46. }
  47. inline void pthread_lock::wait(unsigned long millisecs)
  48. {
  49. struct timespec ts;
  50. timespec_for(&ts,millisecs);
  51. int code = pthread_cond_timedwait(&_cond, &_mutex, &ts);
  52. ASSERT(code == 0 || code == ETIMEDOUT, "timed wait failed,error:%s",strerror(code));
  53. }
  54. inline void pthread_lock::notify()
  55. {
  56. pthread_cond_signal(&_cond);
  57. }
  58. inline void pthread_lock::notify_all()
  59. {
  60. pthread_cond_broadcast(&_cond);
  61. }
  62. }
  63. #endif