ced79d3a78e44b26310057ed3de64d835c4e3d9e
[shibboleth/cpp-xmltooling.git] / xmltooling / Lockable.h
1 /*
2  *  Copyright 2001-2010 Internet2
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * @file xmltooling/Lockable.h
19  * 
20  * Locking abstraction.
21  */
22
23 #ifndef __xmltooling_lockable_h__
24 #define __xmltooling_lockable_h__
25
26 #include <xmltooling/base.h>
27
28 namespace xmltooling {
29
30     /**
31      * Abstract mixin interface for interfaces that support locking
32      */
33     class XMLTOOL_API Lockable
34     {
35     protected:
36         Lockable();
37     public:
38         virtual ~Lockable();
39         
40         /**
41          * Lock the associated object for exclusive access.
42          * 
43          * @return a pointer to the object being locked
44          */
45         virtual Lockable* lock()=0;
46
47         /**
48          * Unlock the associated object from exclusive access.
49          */
50         virtual void unlock()=0;
51     };
52
53     /**
54      * RAII wrapper for lockable objects to ensure lock release
55      */
56     class XMLTOOL_API Locker
57     {
58     MAKE_NONCOPYABLE(Locker);
59     public:
60         /**
61          * Optionally locks an object and stores it for later release.
62          * 
63          * @param lockee    pointer to an object to hold, and optionally lock
64          * @param lock      true iff object is not yet locked
65          */
66         Locker(Lockable* lockee=nullptr, bool lock=true);
67
68         /**
69          * Optionally locks an object and stores it for later release.
70          * If an object is already held, it is unlocked and detached.
71          * 
72          * @param lockee    pointer to an object to hold, and optionally lock
73          * @param lock      true iff object is not yet locked
74          */
75         void assign(Lockable* lockee=nullptr, bool lock=true);
76         
77         /**
78          * Destructor releases lock on held pointer, if any.
79          */
80         ~Locker();
81         
82     private:
83         Lockable* m_lockee;
84     };
85
86 };
87
88 #endif /* __xmltooling_lockable_h__ */