-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreaderwrite.cpp
More file actions
115 lines (94 loc) · 2.66 KB
/
readerwrite.cpp
File metadata and controls
115 lines (94 loc) · 2.66 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
#include <bits/stdc++.h>
#include <iostream>
#include <mutex>
#include <thread>
#include <condition_variable>
using namespace std;
// Multiple Readers, Single writer only at a time
class RWController {
mutex database;
condition_variable can_read;
condition_variable can_write;
int active_readers = 0;
int active_writers = 0;
int waiting_readers = 0;
int waiting_writers = 0;
public:
// Called before a reader enters
void reader_enter() {
unique_lock<mutex> lock(database);
waiting_readers++;
can_read.wait(lock, [&] {
return (waiting_writers + active_writers == 0);
});
waiting_readers--;
active_readers++;
// lock.unlock();
}
// Called after a reader exits
void reader_exit() {
unique_lock<mutex> lock(database);
active_readers--;
if (active_readers == 0 && waiting_writers > 0) {
can_write.notify_one();
}
// lock.unlock();
}
// Called before a writer enters
void writer_enter() {
unique_lock<mutex> lock(database);
waiting_writers++;
can_write.wait(lock, [&] {
return (active_readers + active_writers == 0);
});
waiting_writers--;
active_writers++;
// lock.unlock();
}
// Called after a writer exits
void writer_exit() {
unique_lock<mutex> lock(database);
active_writers--;
if (waiting_writers == 0) {
can_read.notify_all();
} else can_write.notify_one();
// lock.unlock();
}
};
void reader(RWController& c, int& resource, int id) {
c.reader_enter();
int value = resource;
cout << "Reader " << id << " read data" << value << endl;
c.reader_exit();
// return value;
};
void writer(RWController& c, int& resource, int value, int id) {
c.writer_enter();
value += resource;
resource = value;
cout << "Writer " << id << " wrote data" << value << endl;
c.writer_exit();
// return value;
}
int main() {
int resource = 0;
RWController c;
// writer 1
thread writer1(writer, ref(c), ref(resource), 1, 1);
// readers 1,2
thread reader1(reader, ref(c), ref(resource), 1);
thread reader2(reader, ref(c), ref(resource), 2);
// writer 2
thread writer2(writer, ref(c), ref(resource), 2, 2);
// readers 3,4
thread reader3(reader, ref(c), ref(resource), 3);
thread reader4(reader, ref(c), ref(resource), 4);
writer1.join();
reader1.join();
reader2.join();
writer2.join();
reader3.join();
reader4.join();
cout << "All threads have finished execution." << endl;
return 0;
}