RCFProto
 All Classes Functions Typedefs
scoped_lock.hpp
1 
2 //******************************************************************************
3 // RCF - Remote Call Framework
4 //
5 // Copyright (c) 2005 - 2013, Delta V Software. All rights reserved.
6 // http://www.deltavsoft.com
7 //
8 // RCF is distributed under dual licenses - closed source or GPL.
9 // Consult your particular license for conditions of use.
10 //
11 // If you have not purchased a commercial license, you are using RCF
12 // under GPL terms.
13 //
14 // Version: 2.0
15 // Contact: support <at> deltavsoft.com
16 //
17 //******************************************************************************
18 
19 //
20 // detail/scoped_lock.hpp
21 // ~~~~~~~~~~~~~~~~~~~~~~
22 //
23 // Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com)
24 //
25 // Distributed under the Boost Software License, Version 1.0. (See accompanying
26 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
27 //
28 
29 #ifndef RCF_DETAIL_SCOPED_LOCK_HPP
30 #define RCF_DETAIL_SCOPED_LOCK_HPP
31 
32 #if defined(_MSC_VER) && (_MSC_VER >= 1200)
33 # pragma once
34 #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
35 
36 #include <RCF/thread/push_options.hpp>
37 
38 namespace RCF {
39 namespace detail {
40 
41 // Helper class to lock and unlock a mutex automatically.
42 template <typename Mutex>
43 class scoped_lock
44  : private noncopyable
45 {
46 public:
47  // Constructor acquires the lock.
48  scoped_lock(Mutex& m, bool initiallyLocked = true)
49  : mutex_(m)
50  {
51  locked_ = false;
52  if (initiallyLocked)
53  {
54  mutex_.lock();
55  locked_ = true;
56  }
57  }
58 
59  // Destructor releases the lock.
60  ~scoped_lock()
61  {
62  if (locked_)
63  mutex_.unlock();
64  }
65 
66  // Explicitly acquire the lock.
67  void lock()
68  {
69  if (!locked_)
70  {
71  mutex_.lock();
72  locked_ = true;
73  }
74  }
75 
76  // Explicitly release the lock.
77  void unlock()
78  {
79  if (locked_)
80  {
81  mutex_.unlock();
82  locked_ = false;
83  }
84  }
85 
86  // Test whether the lock is held.
87  bool locked() const
88  {
89  return locked_;
90  }
91 
92  // Get the underlying mutex.
93  Mutex& mutex()
94  {
95  return mutex_;
96  }
97 
98 private:
99  // The underlying mutex.
100  Mutex& mutex_;
101 
102  // Whether the mutex is currently locked or unlocked.
103  bool locked_;
104 };
105 
106 } // namespace detail
107 } // namespace RCF
108 
109 #include <RCF/thread/pop_options.hpp>
110 
111 #endif // RCF_DETAIL_SCOPED_LOCK_HPP