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