Line data Source code
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 : 9 : #ifndef BOOST_POOL_GUARD_HPP 10 : #define BOOST_POOL_GUARD_HPP 11 : 12 : /*! 13 : \file 14 : \brief Extremely Light-Weight guard class. 15 : \details Auto-lock/unlock-er 16 : detail/guard.hpp provides a type guard<Mutex> 17 : that allows scoped access to the Mutex's locking and unlocking operations. 18 : It is used to ensure that a Mutex is unlocked, even if an exception is thrown. 19 : */ 20 : 21 : namespace boost { 22 : 23 : namespace details { 24 : namespace pool { 25 : 26 : template <typename Mutex> //!< \tparam Mutex (platform-specific) mutex class. 27 : class guard 28 : { //! Locks the mutex, binding guard<Mutex> to Mutex. 29 : /*! Example: 30 : Given a (platform-specific) mutex class, we can wrap code as follows: 31 : 32 : extern mutex global_lock; 33 : 34 : static void f() 35 : { 36 : boost::details::pool::guard<mutex> g(global_lock); 37 : // g's constructor locks "global_lock" 38 : 39 : ... // do anything: 40 : // throw exceptions 41 : // return 42 : // or just fall through 43 : } // g's destructor unlocks "global_lock" 44 : */ 45 : private: 46 : Mutex & mtx; 47 : 48 : guard(const guard &); //!< Guards the mutex, ensuring unlocked on destruction, even if exception is thrown. 49 : void operator=(const guard &); 50 : 51 : public: 52 712 : explicit guard(Mutex & nmtx) 53 712 : :mtx(nmtx) 54 : { //! Locks the mutex of the guard class. 55 712 : mtx.lock(); 56 : } 57 : 58 712 : ~guard() 59 : { //! destructor unlocks the mutex of the guard class. 60 712 : mtx.unlock(); 61 712 : } 62 : }; // class guard 63 : 64 : } // namespace pool 65 : } // namespace details 66 : 67 : } // namespace boost 68 : 69 : #endif