-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcbuff-mlocked.cpp
More file actions
120 lines (105 loc) · 2.54 KB
/
cbuff-mlocked.cpp
File metadata and controls
120 lines (105 loc) · 2.54 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
116
117
118
119
120
// Circular Buffer.
// Producer enqueues twice the input.
// Fixes after review from Chat-GPT
#include "cbuff-mlocked.h"
#include <thread>
#include <mutex>
using namespace std;
CQueue* CQueue::_cbInstance = nullptr;
void
CQueue::printQueue() {
cout << "-----------PRINT QUEUE-------- " << endl ;
cout << "head " << _head << endl;
cout << "tail " << _tail << endl;
if (_size == 0) {
cout << "Queue is empty" << endl;
cout << "-------------------------------------------" << endl;
return;
}
int index = _head;
for (int i=0; i < _size; i++) {
cout << _arr[index] << " ";
index = (index+1)%capacity;
}
cout << endl;
cout << "-------------------------------------------" << endl;
}
bool
CQueue::isFull() {
if (_size == capacity) {
return true;
}
return false;
}
bool
CQueue::isEmpty() {
if (_size == 0) {
return true;
}
return false;
}
int
CQueue::dequeue() {
int val = _arr[_head];
_head = (_head+1)%capacity;
_size -= 1;
return val;
}
bool
CQueue::enqueue(int num) {
_tail = (_head+_size)%capacity;
_arr[_tail] = num;
_size += 1;
cout << "Enqueued val: " << _arr[_tail] << endl;
return true;
}
void Producer() {
CQueue *_cBuff = CQueue::GetInstance();
int input;
while(true) {
unique_lock<mutex> plck(_cBuff->_cvlck);
_cBuff->_cvp.wait(plck, [&_cBuff](){
cout << "Inside producer lambda isfull " << _cBuff->isFull() << endl;
return !_cBuff->isFull(); });
cin >> input;
_cBuff->enqueue(2*input);
_cBuff->printQueue();
_cBuff->_cvc.notify_one();
}
}
void Consumer() {
CQueue *_cBuff = CQueue::GetInstance();
int val;
while(true) {
unique_lock<mutex> plck(_cBuff->_cvlck);
_cBuff->_cvc.wait(plck, [&_cBuff](){
cout << "Inside consumer lambda isempty " << _cBuff->isEmpty() << endl;
return !_cBuff->isEmpty(); });
while (!_cBuff->isEmpty()) {
val = _cBuff->dequeue();
cout << "Dequeud val: " << val << endl;
}
_cBuff->printQueue();
_cBuff->_cvp.notify_one();
}
}
CQueue*
CQueue::GetInstance() {
if (_cbInstance != nullptr) {
return _cbInstance;
}
int capacity;
cout << "ENTER BUFFER CAPCITY: ";
cin >> capacity;
_cbInstance = new CQueue(capacity);
cout << "Used capacity: " << capacity << endl;
return _cbInstance;
}
int main() {
CQueue::GetInstance();
thread t1(Producer);
thread t2(Consumer);
t1.join();
t2.join();
return 0;
}