Unify cmutex class
[platform/core/api/sensor.git] / src / shared / cmutex.h
1 /*
2  * sensord
3  *
4  * Copyright (c) 2013 Samsung Electronics Co., Ltd.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  */
19
20 #ifndef _CMUTEX_H_
21 #define _CMUTEX_H_
22
23 #include <pthread.h>
24
25 namespace sensor {
26
27 #ifndef MICROSECONDS
28 #define MICROSECONDS(tv) ((tv.tv_sec * 1000000ll) + tv.tv_usec)
29 #endif
30
31 #ifdef _LOCK_DEBUG
32 #define AUTOLOCK(x)      Autolock x##_autolock((x), #x, __MODULE__, __func__, __LINE__)
33 #define LOCK(x)          (x).lock(#x, __MODULE__, __func__, __LINE__)
34 #define UNLOCK(x)        (x).unlock()
35 #else
36 #define AUTOLOCK(x)      Autolock x##_autolock((x))
37 #define LOCK(x)          (x).lock()
38 #define UNLOCK(x)        (x).unlock()
39 #endif
40
41 class cmutex {
42 public:
43         cmutex();
44         virtual ~cmutex();
45
46         void lock(void);
47         void lock(const char* expr, const char *module, const char *func, int line);
48         void unlock(void);
49         int try_lock(void);
50
51 protected:
52         int lock_impl(void);
53         int try_lock_impl(void);
54         int unlock_impl(void);
55
56 private:
57         pthread_mutex_t m_mutex;
58         static const int OWNER_INFO_LEN = 256;
59         char m_owner_info[OWNER_INFO_LEN];
60 };
61
62 class Autolock {
63 private:
64         cmutex& m_lock;
65 public:
66         Autolock(cmutex &m, const char* expr, const char *module, const char *func, int line);
67         Autolock(cmutex &m);
68         ~Autolock();
69 };
70
71 }
72 #endif /* _CMUTEX_H_ */