Ice 3.7 C++98 API Reference
Loading...
Searching...
No Matches
Lock.h
Go to the documentation of this file.
1//
2// Copyright (c) ZeroC, Inc. All rights reserved.
3//
4
5#ifndef ICE_UTIL_LOCK_H
6#define ICE_UTIL_LOCK_H
7
8#include <IceUtil/Config.h>
10
11namespace IceUtil
12{
13
14//
15// Forward declarations.
16//
17class Cond;
18
19// LockT and TryLockT are the preferred construct to lock/tryLock/unlock
20// simple and recursive mutexes. You typically allocate them on the
21// stack to hold a lock on a mutex.
22// LockT and TryLockT are not recursive: you cannot acquire several times
23// in a row a lock with the same Lock or TryLock object.
24//
25// We must name this LockT instead of Lock, because otherwise some
26// compilers (such as Sun C++ 5.4) have problems with constructs
27// such as:
28//
29// class Foo
30// {
31// // ...
32// typedef Lock<Mutex> Lock;
33// }
34//
35template <typename T>
36class LockT
37{
38public:
39
40 LockT(const T& mutex) :
41 _mutex(mutex)
42 {
43 _mutex.lock();
44 _acquired = true;
45 }
46
48 {
49 if (_acquired)
50 {
51 _mutex.unlock();
52 }
53 }
54
55 void acquire() const
56 {
57 if (_acquired)
58 {
59 throw ThreadLockedException(__FILE__, __LINE__);
60 }
61 _mutex.lock();
62 _acquired = true;
63 }
64
65 bool tryAcquire() const
66 {
67 if (_acquired)
68 {
69 throw ThreadLockedException(__FILE__, __LINE__);
70 }
71 _acquired = _mutex.tryLock();
72 return _acquired;
73 }
74
75 void release() const
76 {
77 if (!_acquired)
78 {
79 throw ThreadLockedException(__FILE__, __LINE__);
80 }
81 _mutex.unlock();
82 _acquired = false;
83 }
84
85 bool acquired() const
86 {
87 return _acquired;
88 }
89
90protected:
91
92 // TryLockT's contructor
93 LockT(const T& mutex, bool) :
94 _mutex(mutex)
95 {
96 _acquired = _mutex.tryLock();
97 }
98
99private:
100
101 // Not implemented; prevents accidental use.
102 //
103 LockT(const LockT&);
104 LockT& operator=(const LockT&);
105
106 const T& _mutex;
107 mutable bool _acquired;
108
109 friend class Cond;
110};
111
112//
113// Must be named TryLockT, not TryLock. See the comment for LockT for
114// an explanation.
115//
116template <typename T>
117class TryLockT : public LockT<T>
118{
119public:
120
121 TryLockT(const T& mutex) :
122 LockT<T>(mutex, true)
123 {}
124};
125
126} // End namespace IceUtil
127
128#endif
Definition Cond.h:53
Definition Lock.h:37
bool tryAcquire() const
Definition Lock.h:65
LockT(const T &mutex, bool)
Definition Lock.h:93
LockT(const T &mutex)
Definition Lock.h:40
friend class Cond
Definition Lock.h:109
void acquire() const
Definition Lock.h:55
void release() const
Definition Lock.h:75
~LockT()
Definition Lock.h:47
bool acquired() const
Definition Lock.h:85
Definition ThreadException.h:27
TryLockT(const T &mutex)
Definition Lock.h:121
Definition Cond.h:39