locking_ptr.hpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*! \file
  2. * \brief The locking_ptr is smart pointer with a scoped locking mechanism.
  3. *
  4. * The class is a wrapper for a volatile pointer. It enables synchronized access to the
  5. * internal pointer by locking the passed mutex.
  6. * locking_ptr is based on Andrei Alexandrescu's LockingPtr. For more information
  7. * see article "volatile - Multithreaded Programmer's Best Friend" by A. Alexandrescu.
  8. *
  9. *
  10. * Copyright (c) 2005-2007 Philipp Henkel
  11. *
  12. * Use, modification, and distribution are subject to the
  13. * Boost Software License, Version 1.0. (See accompanying file
  14. * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  15. *
  16. * http://threadpool.sourceforge.net
  17. *
  18. */
  19. #ifndef THREADPOOL_DETAIL_LOCKING_PTR_HPP_INCLUDED
  20. #define THREADPOOL_DETAIL_LOCKING_PTR_HPP_INCLUDED
  21. #include <boost/utility.hpp>
  22. #include <boost/thread/mutex.hpp>
  23. namespace boost { namespace threadpool { namespace detail
  24. {
  25. /*! \brief Smart pointer with a scoped locking mechanism.
  26. *
  27. * This class is a wrapper for a volatile pointer. It enables synchronized access to the
  28. * internal pointer by locking the passed mutex.
  29. */
  30. template <typename T, typename Mutex>
  31. class locking_ptr
  32. : private noncopyable
  33. {
  34. T* m_obj; //!< The instance pointer.
  35. Mutex & m_mutex; //!< Mutex is used for scoped locking.
  36. public:
  37. /// Constructor.
  38. locking_ptr(volatile T& obj, const volatile Mutex& mtx)
  39. : m_obj(const_cast<T*>(&obj))
  40. , m_mutex(*const_cast<Mutex*>(&mtx))
  41. {
  42. // Lock mutex
  43. m_mutex.lock();
  44. }
  45. /// Destructor.
  46. ~locking_ptr()
  47. {
  48. // Unlock mutex
  49. m_mutex.unlock();
  50. }
  51. /*! Returns a reference to the stored instance.
  52. * \return The instance's reference.
  53. */
  54. T& operator*() const
  55. {
  56. return *m_obj;
  57. }
  58. /*! Returns a pointer to the stored instance.
  59. * \return The instance's pointer.
  60. */
  61. T* operator->() const
  62. {
  63. return m_obj;
  64. }
  65. };
  66. } } } // namespace boost::threadpool::detail
  67. #endif // THREADPOOL_DETAIL_LOCKING_PTR_HPP_INCLUDED