blob: 66749c5336b250a04bc52b8549fcec2d785f8abc
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 | public: |
23 | enum { |
24 | PRIVATE = 0, |
25 | SHARED = 1 |
26 | }; |
27 | |
28 | CMutex(); |
29 | CMutex(const char *name); |
30 | CMutex(int type, const char *name = NULL); |
31 | ~CMutex(); |
32 | |
33 | // lock or unlock the mutex |
34 | int lock(); |
35 | void unlock(); |
36 | |
37 | // lock if possible; returns 0 on success, error otherwise |
38 | int tryLock(); |
39 | |
40 | // Manages the mutex automatically. It'll be locked when Autolock is |
41 | // constructed and released when Autolock goes out of scope. |
42 | class Autolock { |
43 | public: |
44 | inline Autolock(CMutex &mutex) : mLock(mutex) |
45 | { |
46 | mLock.lock(); |
47 | } |
48 | inline Autolock(CMutex *mutex) : mLock(*mutex) |
49 | { |
50 | mLock.lock(); |
51 | } |
52 | inline ~Autolock() |
53 | { |
54 | mLock.unlock(); |
55 | } |
56 | private: |
57 | CMutex &mLock; |
58 | }; |
59 | |
60 | private: |
61 | friend class CCondition; |
62 | |
63 | // A mutex cannot be copied |
64 | CMutex(const CMutex &); |
65 | CMutex &operator = (const CMutex &); |
66 | |
67 | pthread_mutex_t mMutex; |
68 | }; |
69 | |
70 | inline CMutex::CMutex() |
71 | { |
72 | pthread_mutex_init(&mMutex, NULL); |
73 | } |
74 | |
75 | inline CMutex::CMutex(const char *name __unused) |
76 | { |
77 | pthread_mutex_init(&mMutex, NULL); |
78 | } |
79 | |
80 | inline CMutex::CMutex(int type, const char *name __unused) |
81 | { |
82 | if (type == SHARED) { |
83 | pthread_mutexattr_t attr; |
84 | pthread_mutexattr_init(&attr); |
85 | pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); |
86 | pthread_mutex_init(&mMutex, &attr); |
87 | pthread_mutexattr_destroy(&attr); |
88 | } else { |
89 | pthread_mutex_init(&mMutex, NULL); |
90 | } |
91 | } |
92 | |
93 | inline CMutex::~CMutex() |
94 | { |
95 | pthread_mutex_destroy(&mMutex); |
96 | } |
97 | |
98 | inline int CMutex::lock() |
99 | { |
100 | return -pthread_mutex_lock(&mMutex); |
101 | } |
102 | |
103 | inline void CMutex::unlock() |
104 | { |
105 | pthread_mutex_unlock(&mMutex); |
106 | } |
107 | |
108 | inline int CMutex::tryLock() |
109 | { |
110 | return -pthread_mutex_trylock(&mMutex); |
111 | } |
112 | |
113 | //typedef CMutex::Autolock AutoMutex; |
114 | |
115 | #endif |
116 |