-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
115 lines (101 loc) · 2.7 KB
/
main.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <iostream>
#include <semaphore.h>
#include <ctime>
#include <unistd.h>
#include <queue>
#include <thread>
using namespace std;
int counter;
int bufferSize;
int numOfThreads;
sem_t wsem, mutex, notempty, notfull;
int t;
queue<int> buffer;
int randomNumber()
{
srand(clock());
return rand() % 1000000 + 100;
}
void reader()
{
while (true)
{
cout << "Monitor thread: waiting to read counter." << endl;
sem_wait(¬full);
sem_wait(&mutex);
sem_wait(&wsem);
cout << "Monitor thread: reading a counter of value = " << counter << endl;
if (buffer.size() < bufferSize)
{
buffer.push(counter);
cout << "Monitor thread: inserted value in buffer = " << buffer.back() << endl;
cout << "Monitor thread: inserted value in position = " << buffer.size() - 1 << endl;
}
else
{
cout << "Monitor thread: buffer is full!" << endl;
}
counter = 0;
sem_post(¬empty);
sem_post(&mutex);
sem_post(&wsem);
usleep(t);
}
}
void writer(int threadId)
{
cout << "Thread " << threadId << ": recieved a message." << endl;
while (true)
{
cout << "Thread " << threadId << ": waiting to write." << endl;
sem_wait(&wsem);
counter++;
cout << "Thread " << threadId << ": now adding to counter, counter value = " << counter << endl;
sem_post(&wsem);
usleep(randomNumber());
}
}
void consumer()
{
int pos = 0;
while (true)
{
if (buffer.size() == 0)
cout << "Collector thread: nothing is in the bufer!" << endl;
sem_wait(¬empty);
sem_wait(&mutex);
cout << "Collector thread: collected value = " << buffer.front() << endl;
cout << "Collector thread: collected value from position = " << pos++ % bufferSize << endl;
buffer.pop();
sem_post(¬full);
sem_post(&mutex);
usleep(randomNumber());
}
}
int main()
{
cout << "Insert the number of threads: " << endl;
cin >> numOfThreads;
cout << "Insert the size of buffer: " << endl;
cin >> bufferSize;
sem_init(&wsem, 0, 1);
sem_init(¬full, 0, bufferSize);
sem_init(¬empty, 0, 0);
sem_init(&mutex, 0, 1);
cout << "Insert size of t for monitor: " << endl;
cin >> t;
std::thread writers[numOfThreads];
std::thread monitor = thread(reader);
std::thread collector = thread(consumer);
for (int i = 0; i < numOfThreads; i++)
{
writers[i] = thread(writer, i);
}
monitor.join();
collector.join();
for (int i = 0; i < numOfThreads; i++)
{
writers[i].join();
}
return 0;
}