Implementing the Producer-Consumer Algorithm in C++

#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

*/

One thought on “Implementing the Producer-Consumer Algorithm in C++”

Leave a Reply to Adam Parker Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.