0339d08c597259ebc8be0c61987a61b6afaf25fc
[platform/core/connectivity/smartcard-service.git] / common / include / Lock.h
1 /*
2  * Copyright (c) 2012, 2013 Samsung Electronics Co., Ltd.
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 #ifndef LOCK_H_
18 #define LOCK_H_
19
20 #include <pthread.h>
21
22 #include "Debug.h"
23
24 namespace smartcard_service_api
25 {
26         class EXPORT Lock
27         {
28         public:
29                 virtual ~Lock() {};
30                 virtual void lock() = 0;
31                 virtual void unlock() = 0;
32         };
33
34         class PMutex : public Lock
35         {
36         private:
37                 pthread_mutex_t mutex;
38
39         public:
40                 PMutex() { pthread_mutex_init(&mutex, NULL); }
41                 ~PMutex() { pthread_mutex_destroy(&mutex); }
42
43                 inline void lock() { pthread_mutex_lock(&mutex); }
44                 inline void unlock() { pthread_mutex_unlock(&mutex); }
45         };
46 #define TOKENPASTE(x, y) x ## y
47 #define TOKENPASTE2(x, y) TOKENPASTE(x, y)
48 #define SCOPE_LOCK(X) \
49         if (const AutoLockHelper& TOKENPASTE2(lock_, __LINE__) = makeAutoLock(X))
50
51         class EXPORT AutoLockHelper
52         {
53         public:
54                 inline operator bool() const
55                 {
56                         return true;
57                 }
58         };
59
60         template<typename T>
61         class EXPORT AutoLock : public AutoLockHelper
62         {
63         private:
64                 T *lock;
65
66         public:
67                 AutoLock(const AutoLock &_lock) { lock = _lock.lock; }
68                 AutoLock(T& _lock) : lock(&_lock) { lock->lock(); }
69                 ~AutoLock() { lock->unlock(); }
70         };
71
72         template<typename T>
73         inline AutoLock<T> makeAutoLock(T& lock)
74         {
75                 return AutoLock<T>(lock);
76         }
77
78 } /* namespace smartcard_service_api */
79 #endif /* SCOPELOCK_H_ */