forked from dmoulding/vld
-
Notifications
You must be signed in to change notification settings - Fork 315
/
Copy pathcriticalsection.h
89 lines (77 loc) · 1.8 KB
/
criticalsection.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
#pragma once
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
// you should consider CriticalSectionLocker<> whenever possible instead of
// directly working with CriticalSection class - it is safer
class CriticalSection
{
public:
void Initialize()
{
m_critRegion.OwningThread = 0;
__try {
InitializeCriticalSection(&m_critRegion);
} __except (GetExceptionCode() == STATUS_NO_MEMORY ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
assert(FALSE);
}
}
void Delete() { DeleteCriticalSection(&m_critRegion); }
// enter the section
void Enter()
{
ULONG_PTR ownerThreadId = (ULONG_PTR)m_critRegion.OwningThread;
UNREFERENCED_PARAMETER(ownerThreadId);
EnterCriticalSection(&m_critRegion);
}
bool IsLocked()
{
return (m_critRegion.OwningThread != NULL);
}
bool IsLockedByCurrentThread()
{
if (m_critRegion.OwningThread == NULL)
return false;
HANDLE ownerThreadId = (HANDLE)GetCurrentThreadId();
return m_critRegion.OwningThread == ownerThreadId;
}
// try enter the section
bool TryEnter() { return (TryEnterCriticalSection(&m_critRegion) != 0); }
// leave the critical section
void Leave() { LeaveCriticalSection(&m_critRegion); }
private:
CRITICAL_SECTION m_critRegion;
};
template<typename T = CriticalSection>
class CriticalSectionLocker
{
public:
CriticalSectionLocker(T& cs)
: m_leave(false)
, m_critSect(cs)
{
m_critSect.Enter();
}
~CriticalSectionLocker()
{
LeaveLock();
}
void Leave()
{
LeaveLock();
}
private:
void LeaveLock()
{
if (!m_leave)
{
m_critSect.Leave();
m_leave = true;
}
}
CriticalSectionLocker(); // not allowed
CriticalSectionLocker( const CriticalSectionLocker & ); // not allowed
CriticalSectionLocker & operator=( const CriticalSectionLocker & ); // not allowed
bool m_leave;
T& m_critSect;
};