shared_mutex 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // -*-c++-*-
  2. // vim: set ft=cpp:
  3. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  4. file Copyright.txt or https://cmake.org/licensing for details. */
  5. #ifndef cm_shared_mutex
  6. #define cm_shared_mutex
  7. #if __cplusplus >= 201402L || defined(_MSVC_LANG) && _MSVC_LANG >= 201402L
  8. # define CMake_HAVE_CXX_SHARED_LOCK
  9. #endif
  10. #if __cplusplus >= 201703L || defined(_MSVC_LANG) && _MSVC_LANG >= 201703L
  11. # define CMake_HAVE_CXX_SHARED_MUTEX
  12. #endif
  13. #if defined(CMake_HAVE_CXX_SHARED_LOCK)
  14. # include <shared_mutex> // IWYU pragma: export
  15. #endif
  16. #if !defined(CMake_HAVE_CXX_SHARED_MUTEX)
  17. # include "cm_uv.h"
  18. #endif
  19. namespace cm {
  20. #if defined(CMake_HAVE_CXX_SHARED_MUTEX)
  21. using std::shared_mutex;
  22. #else
  23. class shared_mutex
  24. {
  25. uv_rwlock_t _M_;
  26. public:
  27. using native_handle_type = uv_rwlock_t*;
  28. shared_mutex() { uv_rwlock_init(&_M_); }
  29. ~shared_mutex() { uv_rwlock_destroy(&_M_); }
  30. shared_mutex(shared_mutex const&) = delete;
  31. shared_mutex& operator=(shared_mutex const&) = delete;
  32. void lock() { uv_rwlock_wrlock(&_M_); }
  33. bool try_lock() { return uv_rwlock_trywrlock(&_M_) == 0; }
  34. void unlock() { uv_rwlock_wrunlock(&_M_); }
  35. void lock_shared() { uv_rwlock_rdlock(&_M_); }
  36. void unlock_shared() { uv_rwlock_rdunlock(&_M_); }
  37. native_handle_type native_handle() { return &_M_; }
  38. };
  39. #endif
  40. #if defined(CMake_HAVE_CXX_SHARED_LOCK)
  41. using std::shared_lock;
  42. #else
  43. template <typename T>
  44. class shared_lock
  45. {
  46. T& _mutex;
  47. public:
  48. using mutex_type = T;
  49. shared_lock(T& m)
  50. : _mutex(m)
  51. {
  52. _mutex.lock_shared();
  53. }
  54. ~shared_lock() { _mutex.unlock_shared(); }
  55. shared_lock(shared_lock const&) = delete;
  56. shared_lock& operator=(shared_lock const&) = delete;
  57. };
  58. #endif
  59. }
  60. #endif