CARMA C++
ScopedLockManager.h
1 #ifndef CARMA_UTIL_SCOPED_LOCK_MANAGER_H
2 #define CARMA_UTIL_SCOPED_LOCK_MANAGER_H
3 
4 
5 #include "carma/util/checking.h"
6 #include "carma/util/posixErrors.h"
7 
8 
9 namespace carma {
10 namespace util {
11 
12 
70 
71 template< typename M >
73  public:
74  explicit ScopedLockManager( M & m );
75 
76  /* virtual */ ~ScopedLockManager( );
77 
78  void lock( );
79 
80  bool tryLock( );
81 
82  void unlock( );
83 
84  private:
85  // no copying
87  ScopedLockManager & operator=( const ScopedLockManager & );
88 
89  M & m_;
90  bool isLocked_;
91 };
92 
93 
94 } // namespace carma::util
95 } // namespace carma
96 
97 
98 // ******* Below here is simply implementation *******
99 
100 template< typename M >
101 inline
103 m_( m ),
104 isLocked_( false )
105 {
106 }
107 
108 
109 template< typename M >
110 inline
112 try {
113  if ( isLocked_ )
114  logIfPosixError( unlockMutexNoThrow( m_ ) );
115 } catch ( ... ) {
116  // just stifle any exceptions
117 
118  return;
119 }
120 
121 
122 template< typename M >
123 inline void
125 {
126  CARMA_CHECK( isLocked_ == false );
127 
128  lockMutex( m_ );
129 
130  isLocked_ = true;
131 }
132 
133 
134 template< typename M >
135 inline bool
137 {
138  CARMA_CHECK( isLocked_ == false );
139 
140  const bool result = tryLockMutex( m_ );
141 
142  if ( result )
143  isLocked_ = true;
144 
145  return result;
146 }
147 
148 
149 template< typename M >
150 inline void
152 {
153  CARMA_CHECK( isLocked_ );
154 
155  unlockMutex( m_ );
156 
157  isLocked_ = false;
158 }
159 
160 
161 #endif
Header file for the CARMA checked build diagnostic macros.
#define CARMA_CHECK(assertion)
Diagnostic macro for checking an assertion in checked builds.
Definition: checking.h:52