#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<dos.h>
void main() {
int buf[50];
int n;
cout << "\n Enter Buffer Size:";
cin >> n;
int s = 1;
int i, j, k;
int c = 0;
int pd = 0;
int cs = 0;
while (s != 20) {
cout << "\n";
cout << "\n Buffer:";
k = cs % n;
while (k != pd % n) {
cout << buf[k] << "\t";
k++;
if (k == n) {
k = 0;
}
}
i = rand() % 100;
s++;
if (i % 2 == 0) {
//Producer will produce the items
if (c != n) {
buf[pd % n] = s;
cout << "\n Producer Produced:" << s;
pd++;
c++;
} else {
cout << "\n Producer is Sleeping";
}
} else {
//Consumer will consumes the items
if (c != 0) {
k = buf[cs % n];
cout << "\n Consumer Consumed:" << k;
cs++;
c--;
} else {
cout << "\n Consumer is Sleeping";
}
}
}
getch();
}
/* Output
Enter Buffer Size:6
Buffer:
Consumer is Sleeping
Buffer:
Consumer is Sleeping
Buffer:
Producer Produced:4
Buffer:4
Producer Produced:5
Buffer:4 5
Consumer Consumed:4
Buffer:5
Producer Produced:7
Buffer:5 7
Producer Produced:8
Buffer:5 7 8
Producer Produced:9
Buffer:5 7 8 9
Producer Produced:10
Buffer:5 7 8 9 10
Producer Produced:11
Buffer:
Consumer Consumed:5
Buffer:7 8 9 10 11
Consumer Consumed:7
Buffer:8 9 10 11
Consumer Consumed:8
Buffer:9 10 11
Consumer Consumed:9
Buffer:10 11
Consumer Consumed:10
Buffer:11
Consumer Consumed:11
Buffer:
Consumer is Sleeping
Buffer:
Producer Produced:19
Buffer:19
Consumer Consumed:19
*/
Related
One thought on “Implementing the Producer-Consumer Algorithm in C++”
To know the process of the implementation if your device of the Apple is not working well then you should know that from the help of the google drive tech help to gather the knowledge from there.
To know the process of the implementation if your device of the Apple is not working well then you should know that from the help of the google drive tech help to gather the knowledge from there.