scoped_lock.hpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. //
  2. // detail/scoped_lock.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2021 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. //
  7. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. #ifndef BOOST_ASIO_DETAIL_SCOPED_LOCK_HPP
  11. #define BOOST_ASIO_DETAIL_SCOPED_LOCK_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <boost/asio/detail/noncopyable.hpp>
  16. #include <boost/asio/detail/push_options.hpp>
  17. namespace boost {
  18. namespace asio {
  19. namespace detail {
  20. // Helper class to lock and unlock a mutex automatically.
  21. template <typename Mutex>
  22. class scoped_lock
  23. : private noncopyable
  24. {
  25. public:
  26. // Tag type used to distinguish constructors.
  27. enum adopt_lock_t { adopt_lock };
  28. // Constructor adopts a lock that is already held.
  29. scoped_lock(Mutex& m, adopt_lock_t)
  30. : mutex_(m),
  31. locked_(true)
  32. {
  33. }
  34. // Constructor acquires the lock.
  35. explicit scoped_lock(Mutex& m)
  36. : mutex_(m)
  37. {
  38. mutex_.lock();
  39. locked_ = true;
  40. }
  41. // Destructor releases the lock.
  42. ~scoped_lock()
  43. {
  44. if (locked_)
  45. mutex_.unlock();
  46. }
  47. // Explicitly acquire the lock.
  48. void lock()
  49. {
  50. if (!locked_)
  51. {
  52. mutex_.lock();
  53. locked_ = true;
  54. }
  55. }
  56. // Explicitly release the lock.
  57. void unlock()
  58. {
  59. if (locked_)
  60. {
  61. mutex_.unlock();
  62. locked_ = false;
  63. }
  64. }
  65. // Test whether the lock is held.
  66. bool locked() const
  67. {
  68. return locked_;
  69. }
  70. // Get the underlying mutex.
  71. Mutex& mutex()
  72. {
  73. return mutex_;
  74. }
  75. private:
  76. // The underlying mutex.
  77. Mutex& mutex_;
  78. // Whether the mutex is currently locked or unlocked.
  79. bool locked_;
  80. };
  81. } // namespace detail
  82. } // namespace asio
  83. } // namespace boost
  84. #include <boost/asio/detail/pop_options.hpp>
  85. #endif // BOOST_ASIO_DETAIL_SCOPED_LOCK_HPP