2 * Copyright 2005-2007, Ingo Weinhold, bonefish@users.sf.net.
3 * All rights reserved. Distributed under the terms of the MIT License.
5 #ifndef _FSSH_AUTO_LOCKER_H
6 #define _FSSH_AUTO_LOCKER_H
9 #include <fssh_types.h>
14 // AutoLockerStandardLocking
15 template<typename Lockable
>
16 class AutoLockerStandardLocking
{
18 inline bool Lock(Lockable
*lockable
)
20 return lockable
->Lock();
23 inline void Unlock(Lockable
*lockable
)
29 // AutoLockerReadLocking
30 template<typename Lockable
>
31 class AutoLockerReadLocking
{
33 inline bool Lock(Lockable
*lockable
)
35 return lockable
->ReadLock();
38 inline void Unlock(Lockable
*lockable
)
40 lockable
->ReadUnlock();
44 // AutoLockerWriteLocking
45 template<typename Lockable
>
46 class AutoLockerWriteLocking
{
48 inline bool Lock(Lockable
*lockable
)
50 return lockable
->WriteLock();
53 inline void Unlock(Lockable
*lockable
)
55 lockable
->WriteUnlock();
60 template<typename Lockable
,
61 typename Locking
= AutoLockerStandardLocking
<Lockable
> >
64 typedef AutoLocker
<Lockable
, Locking
> ThisClass
;
72 inline AutoLocker(Lockable
*lockable
, bool alreadyLocked
= false,
73 bool lockIfNotLocked
= true)
74 : fLockable(lockable
),
75 fLocked(fLockable
&& alreadyLocked
)
77 if (!alreadyLocked
&& lockIfNotLocked
)
81 inline AutoLocker(Lockable
&lockable
, bool alreadyLocked
= false,
82 bool lockIfNotLocked
= true)
83 : fLockable(&lockable
),
84 fLocked(fLockable
&& alreadyLocked
)
86 if (!alreadyLocked
&& lockIfNotLocked
)
95 inline void SetTo(Lockable
*lockable
, bool alreadyLocked
,
96 bool lockIfNotLocked
= true)
100 fLocked
= alreadyLocked
;
101 if (!alreadyLocked
&& lockIfNotLocked
)
105 inline void SetTo(Lockable
&lockable
, bool alreadyLocked
,
106 bool lockIfNotLocked
= true)
108 SetTo(&lockable
, alreadyLocked
, lockIfNotLocked
);
119 if (fLockable
&& !fLocked
)
120 fLocked
= fLocking
.Lock(fLockable
);
126 if (fLockable
&& fLocked
) {
127 fLocking
.Unlock(fLockable
);
138 inline AutoLocker
<Lockable
, Locking
> &operator=(Lockable
*lockable
)
144 inline AutoLocker
<Lockable
, Locking
> &operator=(Lockable
&lockable
)
150 inline bool IsLocked() const { return fLocked
; }
152 inline operator bool() const { return fLocked
; }
161 } // namespace FSShell
163 using FSShell::AutoLocker
;
165 #endif // _FSSH_AUTO_LOCKER_H