scoped_lock.hpp
Go to the documentation of this file.
00001 //
00002 // scoped_lock.hpp
00003 // ~~~~~~~~~~~~~~~
00004 //
00005 // Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
00006 //
00007 // Distributed under the Boost Software License, Version 1.0. (See accompanying
00008 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
00009 //
00010 
00011 #ifndef ASIO_DETAIL_SCOPED_LOCK_HPP
00012 #define ASIO_DETAIL_SCOPED_LOCK_HPP
00013 
00014 #if defined(_MSC_VER) && (_MSC_VER >= 1200)
00015 # pragma once
00016 #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
00017 
00018 #include "asio/detail/push_options.hpp"
00019 
00020 #include "asio/detail/noncopyable.hpp"
00021 
00022 namespace asio {
00023 namespace detail {
00024 
00025 // Helper class to lock and unlock a mutex automatically.
00026 template <typename Mutex>
00027 class scoped_lock
00028   : private noncopyable
00029 {
00030 public:
00031   // Constructor acquires the lock.
00032   scoped_lock(Mutex& m)
00033     : mutex_(m)
00034   {
00035     mutex_.lock();
00036     locked_ = true;
00037   }
00038 
00039   // Destructor releases the lock.
00040   ~scoped_lock()
00041   {
00042     if (locked_)
00043       mutex_.unlock();
00044   }
00045 
00046   // Explicitly acquire the lock.
00047   void lock()
00048   {
00049     if (!locked_)
00050     {
00051       mutex_.lock();
00052       locked_ = true;
00053     }
00054   }
00055 
00056   // Explicitly release the lock.
00057   void unlock()
00058   {
00059     if (locked_)
00060     {
00061       mutex_.unlock();
00062       locked_ = false;
00063     }
00064   }
00065 
00066   // Test whether the lock is held.
00067   bool locked() const
00068   {
00069     return locked_;
00070   }
00071 
00072   // Get the underlying mutex.
00073   Mutex& mutex()
00074   {
00075     return mutex_;
00076   }
00077 
00078 private:
00079   // The underlying mutex.
00080   Mutex& mutex_;
00081 
00082   // Whether the mutex is currently locked or unlocked.
00083   bool locked_;
00084 };
00085 
00086 } // namespace detail
00087 } // namespace asio
00088 
00089 #include "asio/detail/pop_options.hpp"
00090 
00091 #endif // ASIO_DETAIL_SCOPED_LOCK_HPP
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines


Castor
Author(s): Carpe Noctem
autogenerated on Fri Nov 8 2013 11:05:39