-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample-3.cpp
97 lines (81 loc) · 1.54 KB
/
example-3.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
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
#include <iostream>
#include <vector>
#include "mingw.thread.h"
#include "mingw.mutex.h"
template <typename T, unsigned int size>
class MThArrAssist
{
public:
MThArrAssist()
{
_array = new T[size];
for (auto i = 0; i < size; i++)
{
_array[i] = 0;
}
}
~MThArrAssist()
{
delete[] _array;
}
T read(unsigned int n)
{
if (size > n)
{
_lock.lock();
T res = _array[n];
_lock.unlock();
return res;
}
return 0;
}
write(unsigned int n, T record)
{
if (size > n)
{
_lock.lock();
_array[n] = record;
_lock.unlock();
}
}
private:
std::mutex _lock;
T *_array;
};
const unsigned int N = 256;
void threadWrite(MThArrAssist<int, N> &arr)
{
while (true)
{
arr.write(rand() % N, rand() % 100);
}
}
void threadRead(MThArrAssist<int, N> &arr)
{
while (true)
{
for (unsigned int i = 0; i < N; i++)
{
std::cout << arr.read(i) << std::endl;
}
}
}
int main()
{
MThArrAssist<int, N> array;
std::vector<std::thread> th;
// Run
auto i = 0;
for (; i < rand() % 4; i++)
{
th.push_back(std::thread(threadWrite, std::ref(array)));
}
std::cout << "init " << i << " thread of write" << std::endl;
std::thread reader(threadRead, std::ref(array));
reader.join();
for (auto &t : th)
{
t.join();
}
return 0;
}