Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-18 09:28:44

0001 //
0002 // detail/scoped_lock.hpp
0003 // ~~~~~~~~~~~~~~~~~~~~~~
0004 //
0005 // Copyright (c) 2003-2023 Christopher M. Kohlhoff (chris at kohlhoff dot com)
0006 //
0007 // Distributed under the Boost Software License, Version 1.0. (See accompanying
0008 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
0009 //
0010 
0011 #ifndef BOOST_ASIO_DETAIL_SCOPED_LOCK_HPP
0012 #define BOOST_ASIO_DETAIL_SCOPED_LOCK_HPP
0013 
0014 #if defined(_MSC_VER) && (_MSC_VER >= 1200)
0015 # pragma once
0016 #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
0017 
0018 #include <boost/asio/detail/noncopyable.hpp>
0019 
0020 #include <boost/asio/detail/push_options.hpp>
0021 
0022 namespace boost {
0023 namespace asio {
0024 namespace detail {
0025 
0026 // Helper class to lock and unlock a mutex automatically.
0027 template <typename Mutex>
0028 class scoped_lock
0029   : private noncopyable
0030 {
0031 public:
0032   // Tag type used to distinguish constructors.
0033   enum adopt_lock_t { adopt_lock };
0034 
0035   // Constructor adopts a lock that is already held.
0036   scoped_lock(Mutex& m, adopt_lock_t)
0037     : mutex_(m),
0038       locked_(true)
0039   {
0040   }
0041 
0042   // Constructor acquires the lock.
0043   explicit scoped_lock(Mutex& m)
0044     : mutex_(m)
0045   {
0046     mutex_.lock();
0047     locked_ = true;
0048   }
0049 
0050   // Destructor releases the lock.
0051   ~scoped_lock()
0052   {
0053     if (locked_)
0054       mutex_.unlock();
0055   }
0056 
0057   // Explicitly acquire the lock.
0058   void lock()
0059   {
0060     if (!locked_)
0061     {
0062       mutex_.lock();
0063       locked_ = true;
0064     }
0065   }
0066 
0067   // Explicitly release the lock.
0068   void unlock()
0069   {
0070     if (locked_)
0071     {
0072       mutex_.unlock();
0073       locked_ = false;
0074     }
0075   }
0076 
0077   // Test whether the lock is held.
0078   bool locked() const
0079   {
0080     return locked_;
0081   }
0082 
0083   // Get the underlying mutex.
0084   Mutex& mutex()
0085   {
0086     return mutex_;
0087   }
0088 
0089 private:
0090   // The underlying mutex.
0091   Mutex& mutex_;
0092 
0093   // Whether the mutex is currently locked or unlocked.
0094   bool locked_;
0095 };
0096 
0097 } // namespace detail
0098 } // namespace asio
0099 } // namespace boost
0100 
0101 #include <boost/asio/detail/pop_options.hpp>
0102 
0103 #endif // BOOST_ASIO_DETAIL_SCOPED_LOCK_HPP