CARMA C++
ScopedPthreadMutexLockManager.h
1 #ifndef CARMA_UTIL_SCOPED_PTHREAD_MUTEX_LOCK_MANAGER_H
2 #define CARMA_UTIL_SCOPED_PTHREAD_MUTEX_LOCK_MANAGER_H
3 
4 
5 #include "carma/util/checking.h"
6 #include "carma/util/PthreadMutex.h"
7 #include "carma/util/posixErrors.h"
8 
9 
10 namespace carma {
11 namespace util {
12 
13 
53 
55  public:
56  explicit ScopedPthreadMutexLockManager( PthreadMutex & mutex );
57 
58  /* virtual */ ~ScopedPthreadMutexLockManager( );
59 
60  void LockMutex( );
61 
62  bool TryLockMutex( );
63 
64  void UnlockMutex( );
65 
66  private:
67  // no copying
70 
71  PthreadMutex & mutex_;
72  bool mutexIsLocked_;
73 };
74 
75 
76 } // namespace carma::util
77 } // namespace carma
78 
79 
80 // ******* Below here is simply implementation *******
81 
82 inline
83 carma::util::ScopedPthreadMutexLockManager::ScopedPthreadMutexLockManager( PthreadMutex & mutex ) :
84 mutex_( mutex ),
85 mutexIsLocked_( false )
86 {
87 }
88 
89 
90 inline
91 carma::util::ScopedPthreadMutexLockManager::~ScopedPthreadMutexLockManager( )
92 try {
93  if ( mutexIsLocked_ )
94  logIfPosixError( mutex_.UnlockNoThrow( ) );
95 } catch ( ... ) {
96  // just stifle any exceptions
97 
98  return;
99 }
100 
101 
102 inline void
103 carma::util::ScopedPthreadMutexLockManager::LockMutex( )
104 {
105  CARMA_CHECK( mutexIsLocked_ == false );
106 
107  mutex_.Lock( );
108 
109  mutexIsLocked_ = true;
110 }
111 
112 
113 inline bool
114 carma::util::ScopedPthreadMutexLockManager::TryLockMutex( )
115 {
116  CARMA_CHECK( mutexIsLocked_ == false );
117 
118  bool result = mutex_.TryLock( );
119 
120  if ( result )
121  mutexIsLocked_ = true;
122 
123  return result;
124 }
125 
126 
127 inline void
128 carma::util::ScopedPthreadMutexLockManager::UnlockMutex( )
129 {
130  CARMA_CHECK( mutexIsLocked_ );
131 
132  mutex_.Unlock( );
133 
134  mutexIsLocked_ = false;
135 }
136 
137 
138 #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
A simple wrapper class that makes use of ::pthread_mutex_t easier in a C++ world. ...
Definition: PthreadMutex.h:41