-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathLock.cpp
68 lines (53 loc) · 1008 Bytes
/
Lock.cpp
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
#include "Lock.h"
Mutex::Mutex()
{
InitializeCriticalSection(&_cs);
}
Mutex::~Mutex()
{
DeleteCriticalSection(&_cs);
}
void Mutex::lock()
{
EnterCriticalSection(&_cs);
}
bool Mutex::trylock()
{
return TryEnterCriticalSection(&_cs) == TRUE;
}
void Mutex::unlock()
{
LeaveCriticalSection(&_cs);
}
//////////////////////////////////////////////////////////////////////////
Semaphore::Semaphore(long initVal, long maxVal)
{
_sema = CreateSemaphore(NULL, initVal, maxVal, NULL);
if (_sema == NULL) {
throw __FUNCTION__": CreateSemaphore failed";
}
}
Semaphore::~Semaphore()
{
if (_sema)
CloseHandle(_sema);
}
void Semaphore::lock()
{
WaitForSingleObject(_sema, INFINITE);
}
void Semaphore::unlock()
{
LONG count;
::ReleaseSemaphore(_sema, 1, &count);
}
//////////////////////////////////////////////////////////////////////////
// unit testing
#ifdef _UNIT_TEST
static void test()
{
Mutex lock1, lock2;
MutexGuard guard(&lock1);
MMutexGuard guard2(2, &lock1, &lock2);
}
#endif