Chris@16: // Chris@16: // detail/scoped_lock.hpp Chris@16: // ~~~~~~~~~~~~~~~~~~~~~~ Chris@16: // Chris@101: // Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) Chris@16: // Chris@16: // Distributed under the Boost Software License, Version 1.0. (See accompanying Chris@16: // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) Chris@16: // Chris@16: Chris@16: #ifndef BOOST_ASIO_DETAIL_SCOPED_LOCK_HPP Chris@16: #define BOOST_ASIO_DETAIL_SCOPED_LOCK_HPP Chris@16: Chris@16: #if defined(_MSC_VER) && (_MSC_VER >= 1200) Chris@16: # pragma once Chris@16: #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) Chris@16: Chris@16: #include Chris@16: Chris@16: #include Chris@16: Chris@16: namespace boost { Chris@16: namespace asio { Chris@16: namespace detail { Chris@16: Chris@16: // Helper class to lock and unlock a mutex automatically. Chris@16: template Chris@16: class scoped_lock Chris@16: : private noncopyable Chris@16: { Chris@16: public: Chris@16: // Tag type used to distinguish constructors. Chris@16: enum adopt_lock_t { adopt_lock }; Chris@16: Chris@16: // Constructor adopts a lock that is already held. Chris@16: scoped_lock(Mutex& m, adopt_lock_t) Chris@16: : mutex_(m), Chris@16: locked_(true) Chris@16: { Chris@16: } Chris@16: Chris@16: // Constructor acquires the lock. Chris@16: explicit scoped_lock(Mutex& m) Chris@16: : mutex_(m) Chris@16: { Chris@16: mutex_.lock(); Chris@16: locked_ = true; Chris@16: } Chris@16: Chris@16: // Destructor releases the lock. Chris@16: ~scoped_lock() Chris@16: { Chris@16: if (locked_) Chris@16: mutex_.unlock(); Chris@16: } Chris@16: Chris@16: // Explicitly acquire the lock. Chris@16: void lock() Chris@16: { Chris@16: if (!locked_) Chris@16: { Chris@16: mutex_.lock(); Chris@16: locked_ = true; Chris@16: } Chris@16: } Chris@16: Chris@16: // Explicitly release the lock. Chris@16: void unlock() Chris@16: { Chris@16: if (locked_) Chris@16: { Chris@16: mutex_.unlock(); Chris@16: locked_ = false; Chris@16: } Chris@16: } Chris@16: Chris@16: // Test whether the lock is held. Chris@16: bool locked() const Chris@16: { Chris@16: return locked_; Chris@16: } Chris@16: Chris@16: // Get the underlying mutex. Chris@16: Mutex& mutex() Chris@16: { Chris@16: return mutex_; Chris@16: } Chris@16: Chris@16: private: Chris@16: // The underlying mutex. Chris@16: Mutex& mutex_; Chris@16: Chris@16: // Whether the mutex is currently locked or unlocked. Chris@16: bool locked_; Chris@16: }; Chris@16: Chris@16: } // namespace detail Chris@16: } // namespace asio Chris@16: } // namespace boost Chris@16: Chris@16: #include Chris@16: Chris@16: #endif // BOOST_ASIO_DETAIL_SCOPED_LOCK_HPP