-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
77 lines (66 loc) · 1.51 KB
/
main.cpp
File metadata and controls
77 lines (66 loc) · 1.51 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
#include <unistd.h>
#include <thread>
#include "readwrite.h"
#include "semaphore.h"
using namespace std;
enum processes {B, W, D};
const int NUM_THREADS = 10;
int processSequence[] = {W, B, B, D, B, W, W, B, D, D};
int readersCount = 0;
void reader() {
wait(MUTEX);
readersCount ++;
if(readersCount == 1) {
wait(WRITE);
}
cout << "BALANCE: " << endl;
string data = read();
cout << "Current Balance: " << data << endl;
cout << endl;
readersCount --;
if(readersCount == 0) {
signal(WRITE);
}
signal(MUTEX);
}
void writer() {
wait(WRITE);
write();
cout << endl;
signal(WRITE);
}
void withdrawer() {
wait(WRITE);
cout << "WITHDRAW: " << endl;
withdraw();
cout << endl;
signal(WRITE);
}
void depositer() {
wait(WRITE);
cout << "DEPOSIT: " << endl;
deposit();
cout << endl;
signal(WRITE);
}
int main() {
writer();
vector<thread> threads;
try {
for(int i = 0; i < NUM_THREADS; i++) {
if(processSequence[i] == B) {
threads.push_back(thread(reader));
} else if (processSequence[i] == W){
threads.push_back(thread(withdrawer));
} else {
threads.push_back(thread(depositer));
}
}
} catch(...) {
cout << "Something went wrong :/" << endl;
}
for(auto &th: threads) {
th.join();
}
return 0;
}