-
Notifications
You must be signed in to change notification settings - Fork 0
/
prod_consumer_in_cpp.cpp
87 lines (49 loc) · 1.09 KB
/
prod_consumer_in_cpp.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
//////////////////////////////////////////////////////////////////////////
#include<iostream>
#include<thread>
#include<mutex>
#include<condition_variable>
#include<queue>
using namespace std;
mutex mx;
condition_variable cv;
queue<int> Q;
bool finished = false;
int size = 3;
int buf[3];
int add = 0;
int rem = 0;
int num = 0;
void producer(){
for(auto i=0;i<9;i++){
unique_lock<mutex> lk(mx);
if(num > size) exit(1);
while(num == size) cv.wait(lk);
buf[add] = i;
add = (add+1) % size;
num++;
cv.notify_all();
cout << "\nProducer inserted " << i << endl;
}
return;
}
void consumer(){
while(1){
unique_lock<mutex> lk2(mx);
if(num == 0) cv.wait(lk2);
if(num < 0) exit(1);
int i = buf[rem];
rem = (rem+1) % size;
num -- ;
cv.notify_all();
cout << "\nCOnsumed value " << i << endl;
if(i == 8) break;
}
}
int main(){
thread tobj1(producer);
thread tobj2(consumer);
tobj1.join();
tobj2.join();
return 0;
}