00001 // 00002 // scoped_lock.hpp 00003 // ~~~~~~~~~~~~~~~ 00004 // 00005 // Copyright (c) 2003-2007 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 private: 00067 // The underlying mutex. 00068 Mutex& mutex_; 00069 00070 // Whether the mutex is currently locked or unlocked. 00071 bool locked_; 00072 }; 00073 00074 } // namespace detail 00075 } // namespace asio 00076 00077 #include "asio/detail/pop_options.hpp" 00078 00079 #endif // ASIO_DETAIL_SCOPED_LOCK_HPP
1.5.6