lock_guard.hpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Distributed under the Boost Software License, Version 1.0. (See
  2. // accompanying file LICENSE_1_0.txt or copy at
  3. // http://www.boost.org/LICENSE_1_0.txt)
  4. // (C) Copyright 2007 Anthony Williams
  5. // (C) Copyright 2011-2012 Vicente J. Botet Escriba
  6. #ifndef BOOST_THREAD_LOCK_GUARD_HPP
  7. #define BOOST_THREAD_LOCK_GUARD_HPP
  8. #include <boost/thread/detail/config.hpp>
  9. #include <boost/thread/detail/delete.hpp>
  10. #include <boost/thread/detail/move.hpp>
  11. #include <boost/thread/detail/lockable_wrapper.hpp>
  12. #include <boost/thread/lock_options.hpp>
  13. #if ! defined BOOST_THREAD_PROVIDES_NESTED_LOCKS
  14. #include <boost/thread/is_locked_by_this_thread.hpp>
  15. #include <boost/assert.hpp>
  16. #endif
  17. #include <boost/config/abi_prefix.hpp>
  18. namespace boost
  19. {
  20. template <typename Mutex>
  21. class BOOST_THREAD_SCOPED_CAPABILITY lock_guard
  22. {
  23. private:
  24. Mutex& m;
  25. public:
  26. typedef Mutex mutex_type;
  27. BOOST_THREAD_NO_COPYABLE( lock_guard )
  28. explicit lock_guard(Mutex& m_) BOOST_THREAD_ACQUIRE(m_) :
  29. m(m_)
  30. {
  31. m.lock();
  32. }
  33. lock_guard(Mutex& m_, adopt_lock_t) BOOST_THREAD_REQUIRES(m_) :
  34. m(m_)
  35. {
  36. #if ! defined BOOST_THREAD_PROVIDES_NESTED_LOCKS
  37. BOOST_ASSERT(is_locked_by_this_thread(m));
  38. #endif
  39. }
  40. #if ! defined BOOST_THREAD_NO_CXX11_HDR_INITIALIZER_LIST
  41. lock_guard(std::initializer_list<thread_detail::lockable_wrapper<Mutex> > l_) :
  42. m(*(const_cast<thread_detail::lockable_wrapper<Mutex>*>(l_.begin())->m))
  43. {
  44. m.lock();
  45. }
  46. lock_guard(std::initializer_list<thread_detail::lockable_adopt_wrapper<Mutex> > l_) :
  47. m(*(const_cast<thread_detail::lockable_adopt_wrapper<Mutex>*>(l_.begin())->m))
  48. {
  49. #if ! defined BOOST_THREAD_PROVIDES_NESTED_LOCKS
  50. BOOST_ASSERT(is_locked_by_this_thread(m));
  51. #endif
  52. }
  53. #endif
  54. ~lock_guard() BOOST_THREAD_RELEASE()
  55. {
  56. m.unlock();
  57. }
  58. };
  59. #if ! defined BOOST_THREAD_NO_MAKE_LOCK_GUARD
  60. template <typename Lockable>
  61. lock_guard<Lockable> make_lock_guard(Lockable& mtx)
  62. {
  63. return { thread_detail::lockable_wrapper<Lockable>(mtx) };
  64. }
  65. template <typename Lockable>
  66. lock_guard<Lockable> make_lock_guard(Lockable& mtx, adopt_lock_t)
  67. {
  68. return { thread_detail::lockable_adopt_wrapper<Lockable>(mtx) };
  69. }
  70. #endif
  71. }
  72. #include <boost/config/abi_suffix.hpp>
  73. #endif