blob: 87e9a8e8b2cbbab63523c065a9e19bcef0b97ead
1 | /* |
2 | reference android api, just linux pthread |
3 | */ |
4 | |
5 | #ifndef _TV_UTILS_MUTEX_H |
6 | #define _TV_UTILS_MUTEX_H |
7 | |
8 | #include <stdint.h> |
9 | #include <sys/types.h> |
10 | #include <time.h> |
11 | #include <pthread.h> |
12 | |
13 | class CCondition; |
14 | |
15 | /* |
16 | * Simple mutex class. The implementation is system-dependent. |
17 | * |
18 | * The mutex must be unlocked by the thread that locked it. They are not |
19 | * recursive, i.e. the same thread can't lock it multiple times. |
20 | */ |
21 | class CMutex |
22 | { |
23 | public: |
24 | enum { |
25 | PRIVATE = 0, |
26 | SHARED = 1 |
27 | }; |
28 | |
29 | CMutex(); |
30 | CMutex(const char *name); |
31 | CMutex(int type, const char *name = NULL); |
32 | ~CMutex(); |
33 | |
34 | // lock or unlock the mutex |
35 | int lock(); |
36 | void unlock(); |
37 | |
38 | // lock if possible; returns 0 on success, error otherwise |
39 | int tryLock(); |
40 | |
41 | // Manages the mutex automatically. It'll be locked when Autolock is |
42 | // constructed and released when Autolock goes out of scope. |
43 | class Autolock |
44 | { |
45 | public: |
46 | inline Autolock(CMutex &mutex) : mLock(mutex) |
47 | { |
48 | mLock.lock(); |
49 | } |
50 | inline Autolock(CMutex *mutex) : mLock(*mutex) |
51 | { |
52 | mLock.lock(); |
53 | } |
54 | inline ~Autolock() |
55 | { |
56 | mLock.unlock(); |
57 | } |
58 | private: |
59 | CMutex &mLock; |
60 | }; |
61 | |
62 | private: |
63 | friend class CCondition; |
64 | |
65 | // A mutex cannot be copied |
66 | CMutex(const CMutex &); |
67 | CMutex &operator = (const CMutex &); |
68 | |
69 | pthread_mutex_t mMutex; |
70 | }; |
71 | |
72 | |
73 | |
74 | |
75 | |
76 | inline CMutex::CMutex() |
77 | { |
78 | pthread_mutex_init(&mMutex, NULL); |
79 | } |
80 | inline CMutex::CMutex(const char *name) |
81 | { |
82 | pthread_mutex_init(&mMutex, NULL); |
83 | } |
84 | inline CMutex::CMutex(int type, const char *name) |
85 | { |
86 | if (type == SHARED) { |
87 | pthread_mutexattr_t attr; |
88 | pthread_mutexattr_init(&attr); |
89 | pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); |
90 | pthread_mutex_init(&mMutex, &attr); |
91 | pthread_mutexattr_destroy(&attr); |
92 | } else { |
93 | pthread_mutex_init(&mMutex, NULL); |
94 | } |
95 | } |
96 | inline CMutex::~CMutex() |
97 | { |
98 | pthread_mutex_destroy(&mMutex); |
99 | } |
100 | inline int CMutex::lock() |
101 | { |
102 | return -pthread_mutex_lock(&mMutex); |
103 | } |
104 | inline void CMutex::unlock() |
105 | { |
106 | pthread_mutex_unlock(&mMutex); |
107 | } |
108 | inline int CMutex::tryLock() |
109 | { |
110 | return -pthread_mutex_trylock(&mMutex); |
111 | } |
112 | |
113 | |
114 | //typedef CMutex::Autolock AutoMutex; |
115 | |
116 | #endif |
117 |