今天閑來無事就隨便寫了個線程安全的設計模式,具體代碼如下:
1
#include <iostream>
2
#include <vector>
3
#include <bitset>
4
#include <assert.h>
5
#include <Windows.h>
6
#include <process.h>
7
8
using namespace std;
9
10
class CSingleton
11

{
12
private:
13
class CAssistForSingleton
14
{
15
private:
16
CRITICAL_SECTION m_cs;
17
18
public:
19
CAssistForSingleton()
20
{
21
InitializeCriticalSection(&m_cs);
22
}
23
24
~CAssistForSingleton()
25
{
26
DeleteCriticalSection(&m_cs);
27
}
28
29
public:
30
void Lock()
31
{
32
EnterCriticalSection(&m_cs);
33
}
34
35
void UnLock()
36
{
37
LeaveCriticalSection(&m_cs);
38
}
39
};
40
41
private:
42
static CAssistForSingleton m_refSycObj;
43
static CSingleton *m_pInstance;
44
45
static int m_nData;
46
47
private:
48
CSingleton()
49
{
50
51
}
52
53
public:
54
static CSingleton *GetInstatnce()
55
{
56
m_refSycObj.Lock();
57
if (NULL == m_pInstance)
58
{
59
m_pInstance = new CSingleton;
60
cout<<"new CSingleton"<<endl;
61
}
62
m_refSycObj.UnLock();
63
64
return m_pInstance;
65
}
66
67
public:
68
static int GetData()
69
{
70
return m_nData;
71
}
72
73
static void SetData(int nData)
74
{
75
m_refSycObj.Lock();
76
m_nData = nData;
77
m_refSycObj.UnLock();
78
}
79
};
80
81
CSingleton::CAssistForSingleton CSingleton::m_refSycObj = CSingleton::CAssistForSingleton();
82
CSingleton *CSingleton::m_pInstance = NULL;
83
int CSingleton::m_nData = 0;
84
85
unsigned int WINAPI ThreadFun(void *)
86

{
87
cout<<"Launcher Thread"<<endl;
88
89
for(int i = 0 ; i < 99999999 ; i++)
90
{
91
CSingleton *pSingl = CSingleton::GetInstatnce();
92
if (NULL != pSingl)
93
{
94
pSingl->SetData(i);
95
}
96
97
Sleep(500);
98
}
99
100
return 0;
101
}
102
103
int main(int argv, char *argc[])
104

{
105
uintptr_t HandleThread[10];
106
unsigned int nThreadId = 0;
107
for(int i = 0 ; i < 10 ; i++)
108
{
109
HandleThread[i] = _beginthreadex(NULL, 0, ThreadFun, NULL, 0, &nThreadId);
110
}
111
112
WaitForMultipleObjects(10, (const HANDLE *)HandleThread, TRUE, INFINITE);
113
114
return 0;
115
}
116
117

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

以上就是我的實現,有什么問題歡迎批評指針。