Ice 3.7 C++11 API Reference
MutexPtrTryLock.h
Go to the documentation of this file.
1 //
2 // Copyright (c) ZeroC, Inc. All rights reserved.
3 //
4 
5 #ifndef ICE_UTIL_MUTEX_PTR_TRY_LOCK_H
6 #define ICE_UTIL_MUTEX_PTR_TRY_LOCK_H
7 
8 #include <IceUtil/Config.h>
9 #include <IceUtil/Mutex.h>
10 
11 namespace IceUtilInternal
12 {
13 
14 template<class T>
15 class MutexPtrTryLock
16 {
17 public:
18 
19  MutexPtrTryLock<T>(const T* mutex) :
20  _mutex(mutex),
21  _acquired(false)
22  {
23  if(_mutex)
24  {
25  _acquired = _mutex->tryLock();
26  }
27  }
28 
29  ~MutexPtrTryLock<T>()
30  {
31  if(_mutex && _acquired)
32  {
33  _mutex->unlock();
34  }
35  }
36 
37  void acquire() const
38  {
39  if(_mutex)
40  {
41  _mutex->lock();
42  _acquired = true;
43  }
44  }
45 
46  void release() const
47  {
48  if(_mutex)
49  {
50  if(!_acquired)
51  {
52  throw IceUtil::ThreadLockedException(__FILE__, __LINE__);
53  }
54  _mutex->unlock();
55  _acquired = false;
56  }
57  }
58 
59  bool acquired() const
60  {
61  return _acquired;
62  }
63 
64 private:
65 
66  // Not implemented; prevents accidental use.
67  //
68  MutexPtrTryLock<T>(const MutexPtrTryLock&);
69  MutexPtrTryLock<T>& operator=(const MutexPtrTryLock<T>&);
70 
71  const T* _mutex;
72  mutable bool _acquired;
73 };
74 
75 } // End namespace IceUtilInternal
76 
77 #endif
IceUtil::ThreadLockedException
Definition: ThreadException.h:27
Config.h
Mutex.h