guard.hpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright (C) 2000 Stephen Cleary
  2. //
  3. // Distributed under the Boost Software License, Version 1.0. (See
  4. // accompanying file LICENSE_1_0.txt or copy at
  5. // http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // See http://www.boost.org for updates, documentation, and revision history.
  8. #ifndef BOOST_POOL_GUARD_HPP
  9. #define BOOST_POOL_GUARD_HPP
  10. /*!
  11. \file
  12. \brief Extremely Light-Weight guard class.
  13. \details Auto-lock/unlock-er
  14. detail/guard.hpp provides a type guard<Mutex>
  15. that allows scoped access to the Mutex's locking and unlocking operations.
  16. It is used to ensure that a Mutex is unlocked, even if an exception is thrown.
  17. */
  18. namespace boost {
  19. namespace details {
  20. namespace pool {
  21. template <typename Mutex> //!< \tparam Mutex (platform-specific) mutex class.
  22. class guard
  23. { //! Locks the mutex, binding guard<Mutex> to Mutex.
  24. /*! Example:
  25. Given a (platform-specific) mutex class, we can wrap code as follows:
  26. extern mutex global_lock;
  27. static void f()
  28. {
  29. boost::details::pool::guard<mutex> g(global_lock);
  30. // g's constructor locks "global_lock"
  31. ... // do anything:
  32. // throw exceptions
  33. // return
  34. // or just fall through
  35. } // g's destructor unlocks "global_lock"
  36. */
  37. private:
  38. Mutex & mtx;
  39. guard(const guard &); //!< Guards the mutex, ensuring unlocked on destruction, even if exception is thrown.
  40. void operator=(const guard &);
  41. public:
  42. explicit guard(Mutex & nmtx)
  43. :mtx(nmtx)
  44. { //! Locks the mutex of the guard class.
  45. mtx.lock();
  46. }
  47. ~guard()
  48. { //! destructor unlocks the mutex of the guard class.
  49. mtx.unlock();
  50. }
  51. }; // class guard
  52. } // namespace pool
  53. } // namespace details
  54. } // namespace boost
  55. #endif