summaryrefslogtreecommitdiff
path: root/tvapi/libtv/tvutils/CMutex.h (plain)
blob: 5c91c1afbed1a720574e1b0c50ac77ec175340ac
1/*
2reference 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
13class 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 */
21class CMutex {
22public:
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
60private:
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
71
72
73
74inline CMutex::CMutex()
75{
76 pthread_mutex_init(&mMutex, NULL);
77}
78inline CMutex::CMutex(const char *name)
79{
80 pthread_mutex_init(&mMutex, NULL);
81}
82inline CMutex::CMutex(int type, const char *name)
83{
84 if (type == SHARED) {
85 pthread_mutexattr_t attr;
86 pthread_mutexattr_init(&attr);
87 pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
88 pthread_mutex_init(&mMutex, &attr);
89 pthread_mutexattr_destroy(&attr);
90 } else {
91 pthread_mutex_init(&mMutex, NULL);
92 }
93}
94inline CMutex::~CMutex()
95{
96 pthread_mutex_destroy(&mMutex);
97}
98inline int CMutex::lock()
99{
100 return -pthread_mutex_lock(&mMutex);
101}
102inline void CMutex::unlock()
103{
104 pthread_mutex_unlock(&mMutex);
105}
106inline int CMutex::tryLock()
107{
108 return -pthread_mutex_trylock(&mMutex);
109}
110
111
112//typedef CMutex::Autolock AutoMutex;
113
114#endif
115