scoped_lock.hpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. //
  2. // scoped_lock.hpp
  3. // ~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2008 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/push_options.hpp>
  16. #include <boost/asio/detail/noncopyable.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. // Constructor acquires the lock.
  27. scoped_lock(Mutex& m)
  28. : mutex_(m)
  29. {
  30. mutex_.lock();
  31. locked_ = true;
  32. }
  33. // Destructor releases the lock.
  34. ~scoped_lock()
  35. {
  36. if (locked_)
  37. mutex_.unlock();
  38. }
  39. // Explicitly acquire the lock.
  40. void lock()
  41. {
  42. if (!locked_)
  43. {
  44. mutex_.lock();
  45. locked_ = true;
  46. }
  47. }
  48. // Explicitly release the lock.
  49. void unlock()
  50. {
  51. if (locked_)
  52. {
  53. mutex_.unlock();
  54. locked_ = false;
  55. }
  56. }
  57. // Test whether the lock is held.
  58. bool locked() const
  59. {
  60. return locked_;
  61. }
  62. // Get the underlying mutex.
  63. Mutex& mutex()
  64. {
  65. return mutex_;
  66. }
  67. private:
  68. // The underlying mutex.
  69. Mutex& mutex_;
  70. // Whether the mutex is currently locked or unlocked.
  71. bool locked_;
  72. };
  73. } // namespace detail
  74. } // namespace asio
  75. } // namespace boost
  76. #include <boost/asio/detail/pop_options.hpp>
  77. #endif // BOOST_ASIO_DETAIL_SCOPED_LOCK_HPP