-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtest_rw_lock.cpp
More file actions
142 lines (110 loc) · 2.89 KB
/
test_rw_lock.cpp
File metadata and controls
142 lines (110 loc) · 2.89 KB
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
// test_read_write_lock.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <assert.h>
#include <Windows.h>
#include <time.h>
#include "rw_lock.h"
#include "assist.h"
#define USE_RW_LOCK 1
struct test {
volatile int current;
volatile int buff[1024];
} buff;
HANDLE hMutex;
struct rw_lock lock;
DWORD WINAPI read_thread(LPVOID lp)
{
int ret;
unsigned long cnt = (unsigned long) 0x1ffff;
struct test *t = (struct test *)lp;
while (cnt-- > 0) {
#if USE_RW_LOCK
ret = rwlock_get_read(&lock, 0x7fffffff);
assert(ret == 0);
#else
WaitForSingleObject(hMutex, INFINITE);
#endif
if (t->buff[t->current] == 1) {
static unsigned long cnt = 0;
if (t->current != cnt)
printf("--->read--curr index%d<---\n", t->current);
cnt = t->current;
} else {
printf("--->read--occurs error<---\n");
system("PAUSE");
}
#if USE_RW_LOCK
rwlock_put_read(&lock);
#else
ReleaseMutex(hMutex);
#endif
//Sleep(1);
}
return 0;
}
DWORD WINAPI write_thread(LPVOID lp)
{
int ref;
unsigned long cnt = (unsigned long) 0xf;
struct test *t = (struct test *)lp;
while (cnt-- > 0) {
#if USE_RW_LOCK
ref = rwlock_get_write(&lock, 0x7fffffff);
assert(ref == 0);
#else
WaitForSingleObject(hMutex, INFINITE);
#endif
t->buff[t->current] = 0;
//Sleep(2);
t->current = rand() % 1024;
Sleep(2);
t->buff[t->current]++;
//printf("--->write--curr index%d<---\n", t->current);
#if USE_RW_LOCK
rwlock_put_write(&lock);
#else
ReleaseMutex(hMutex);
#endif
Sleep(100);
}
return 0;
}
HANDLE rt_begin()
{
HANDLE hThread = CreateThread(NULL, 0, read_thread, &buff, 0, NULL);
return hThread;
}
HANDLE wt_begin()
{
HANDLE hThread = CreateThread(NULL, 0, write_thread, &buff, 0, NULL);
return hThread;
}
static int init()
{
memset(&buff, 0, sizeof(buff));
buff.buff[buff.current] = 1;
srand((int)time(NULL));
rwlock_init(&lock);
hMutex = CreateMutex(NULL, FALSE, NULL);
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
int i;
HANDLE htbl[64];
init();
CACL_TAKES_TIME_BEGIN(tt);
for (i = 0; i < 61; i++)
htbl[i] = rt_begin();
htbl[i++] = wt_begin();
htbl[i++] = wt_begin();
htbl[i++] = wt_begin();
DWORD ret = WaitForMultipleObjects(64, htbl, TRUE, INFINITE);
int takes = CACL_TAKES_TIME_END(tt);
printf("-------takes %d ms\n", takes);
system("pause");
while (1)
Sleep(10000);
return 0;
}