shared_mutex 1.6 KB

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