-
Notifications
You must be signed in to change notification settings - Fork 0
/
example-2.cpp
90 lines (76 loc) · 1.43 KB
/
example-2.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
#include <iostream>
#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)
{
for (unsigned int i = 0; i < N; i++)
{
arr.write(i, 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;
// Run
std::thread t1(threadWrite, std::ref(array));
std::thread t2(threadWrite, std::ref(array));
std::thread t3(threadRead, std::ref(array));
t1.join();
t2.join();
t3.join();
return 0;
}