forked from bangerlee/mempool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThreadLock.h
104 lines (89 loc) · 1.49 KB
/
ThreadLock.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
//在网上找了很多关于线程锁的东西,因为我不想让我的内存分配器依赖于ACE的接口。
//一开始觉得找一个这样的类拷贝一个过来,省事。但是发现要不写的太复杂,要不太简单。
//看来还是要自己动笔呀,不过好在我找到了一些比较好的例子。
//加油,不要随便说不可以,要努力去做。因为我坚信。
#ifndef _THREADLOCK_H
#define _THREADLOCK_H
#ifdef WIN32
#include <Windows.h>
#else
#include <pthread.h>
#endif
#ifdef WIN32
#define LOCK_MUTEXT CRITICAL_SECTION
#else
#define LOCK_MUTEXT pthread_mutex_t
#endif
#include "ace/OS.h"
class CThreadLock
{
public:
CThreadLock(void)
{
Init();
};
~CThreadLock()
{
Close();
};
void Init()
{
#ifdef _WIN32
InitializeCriticalSection(&m_lock);
#else
pthread_mutex_init(&m_lock, NULL);
#endif
};
void Close()
{
#ifdef _WIN32
DeleteCriticalSection(&m_lock);
#else
pthread_mutex_destroy(&m_lock);
#endif
}
void Lock()
{
m_Time = ACE_OS::gettimeofday();
#ifdef _WIN32
EnterCriticalSection(&m_lock);
#else
pthread_mutex_lock(&m_lock);
#endif
};
void UnLock()
{
m_Time = ACE_OS::gettimeofday() - m_Time;
#ifdef _WIN32
LeaveCriticalSection(&m_lock);
#else
pthread_mutex_unlock(&m_lock);
#endif
};
private:
LOCK_MUTEXT m_lock;
ACE_Time_Value m_Time;
};
//自动加锁的类
class CAutoLock
{
public:
CAutoLock(CThreadLock* pThreadLock)
{
m_pThreadLock = pThreadLock;
if(NULL != m_pThreadLock)
{
m_pThreadLock->Lock();
}
};
~CAutoLock()
{
if(NULL != m_pThreadLock)
{
m_pThreadLock->UnLock();
}
};
private:
CThreadLock* m_pThreadLock;
};
#endif