scoped_lock.hpp 1.6 KB

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