mutex.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // C++ wrapper for pthread_mutex_t
  2. //
  3. // Platform: ISO C++ 98/11 - POSIX
  4. // $Id$
  5. //
  6. // (c) __vic 2007
  7. #ifndef __VIC_POSIX_MUTEX_H
  8. #define __VIC_POSIX_MUTEX_H
  9. #include<__vic/posix/_cfg.h>
  10. #include<__vic/defs.h>
  11. #include<pthread.h>
  12. namespace __vic { namespace posix {
  13. //////////////////////////////////////////////////////////////////////////////
  14. // Plain non-recursive mutex
  15. class mutex
  16. {
  17. ::pthread_mutex_t mtx
  18. #if __cplusplus >= 201103L
  19. = PTHREAD_MUTEX_INITIALIZER
  20. #endif
  21. ;
  22. #if __cplusplus < 201103L
  23. mutex(const mutex & ); // not implemented
  24. mutex &operator=(const mutex & ); // not implemented
  25. #else
  26. public:
  27. mutex(const mutex & ) = delete;
  28. mutex &operator=(const mutex & ) = delete;
  29. #endif
  30. public:
  31. #if __cplusplus >= 201103L
  32. constexpr mutex() noexcept = default;
  33. #else // C++98
  34. mutex() { ::pthread_mutex_init(&mtx, nullptr); }
  35. #endif
  36. ~mutex() { ::pthread_mutex_destroy(&mtx); }
  37. void lock();
  38. bool try_lock();
  39. bool unlock() noexcept { return ::pthread_mutex_unlock(&mtx) == 0; }
  40. // System-specific handle
  41. ::pthread_mutex_t *handle() { return &mtx; }
  42. const ::pthread_mutex_t *handle() const { return &mtx; }
  43. };
  44. //////////////////////////////////////////////////////////////////////////////
  45. // Lock-guard for mutexes
  46. class mutex_lock : private non_copyable, private non_heap_allocatable
  47. {
  48. ::pthread_mutex_t &mtx;
  49. void lock();
  50. public:
  51. enum adopt_t { adopt };
  52. explicit mutex_lock(mutex &m) : mtx(*m.handle()) { lock(); }
  53. // avoid lock() call in constructor (for already locked mutex)
  54. mutex_lock(mutex &m, adopt_t) : mtx(*m.handle()) {}
  55. // Same constructors for Pthreads mutex
  56. explicit mutex_lock(::pthread_mutex_t &m) : mtx(m) { lock(); }
  57. mutex_lock(::pthread_mutex_t &m, adopt_t) : mtx(m) {}
  58. ~mutex_lock() __VIC_THROWS; // No free store allocation!
  59. };
  60. //////////////////////////////////////////////////////////////////////////////
  61. }} // namespace
  62. #endif // header guard