-
Notifications
You must be signed in to change notification settings - Fork 1
/
AutoLock.h
154 lines (131 loc) · 2.23 KB
/
AutoLock.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
#ifndef UM_COMMON_AUTOLOCK_H_
#define UM_COMMON_AUTOLOCK_H_
namespace UMLink
{
class CCriticalSection;
class CMutex;
template<typename T>
class CAutoLock
{
public:
CAutoLock(T* pLock)
{
m_pLock = pLock;
m_pLock->Lock();
}
~CAutoLock()
{
m_pLock->Unlock();
}
private:
T* m_pLock;
};
typedef CAutoLock<CMutex> CAutoMutex;
typedef CAutoLock<CCriticalSection> CAutoCS;
class CCriticalSection
{
public:
CCriticalSection()
{
InitializeCriticalSection(&m_cs);
}
~CCriticalSection()
{
DeleteCriticalSection(&m_cs);
}
void Lock()
{
EnterCriticalSection(&m_cs);
}
void Unlock()
{
LeaveCriticalSection(&m_cs);
}
private:
CCriticalSection(const CCriticalSection&);
CCriticalSection& operator=(const CCriticalSection&);
private:
CRITICAL_SECTION m_cs;
};
class CMutex
{
public:
CMutex(const char* szName)
: m_hMutex(NULL), m_dErrorCode(NO_ERROR)
{
m_hMutex = CreateMutexA(NULL, false, szName);
m_dErrorCode = GetLastError();
if (m_hMutex == NULL)
{
assert(false);
}
}
~CMutex()
{
if (m_hMutex)
{
CloseHandle(m_hMutex);
m_hMutex = NULL;
}
}
void Lock()
{
WaitForSingleObject(m_hMutex, INFINITE);
}
void Unlock()
{
ReleaseMutex(m_hMutex);
}
bool IsValid()
{
return m_hMutex != NULL;
}
private:
CMutex(const CMutex&);
CMutex& operator=(const CMutex&);
private:
HANDLE m_hMutex;
DWORD m_dErrorCode;
};
class CSemaphore
{
public:
CSemaphore(const char* szName, long lInitNum, long lMaxNum)
: m_hSemaphore(NULL), m_dErrorCode(NO_ERROR)
{
m_hSemaphore = CreateSemaphoreA(NULL, lInitNum, lMaxNum, szName);
m_dErrorCode = GetLastError();
if (m_hSemaphore == NULL)
{
assert(false);
}
}
~CSemaphore()
{
if (m_hSemaphore)
{
CloseHandle(m_hSemaphore);
m_hSemaphore = NULL;
}
}
void Lock()
{
WaitForSingleObject(m_hSemaphore, INFINITE);
}
void Unlock()
{
ReleaseSemaphore(m_hSemaphore, 1, NULL);
}
bool IsValid()
{
return m_hSemaphore != NULL;
}
private:
CSemaphore(const CSemaphore&);
CSemaphore& operator=(const CSemaphore&);
private:
HANDLE m_hSemaphore;
DWORD m_dErrorCode;
};
}
#endif //UM_COMMON_AUTOLOCK_H_