Impemnt Producer Consumer Problem In cpp or c

Impemnt Producer Consumer Problem In cpp or c

PROGRAM:

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<pthread.h>
  4. # define BufferSize 3
  5.  
  6. int mutex=1,full=0,empty=3,x=0;
  7.  
  8.  
  9. void *producer();
  10. void *consumer();
  11. int BufferIndex=0;
  12. char *BUFFER;
  13.  
  14. pthread_cond_t Buffer_Not_Full=PTHREAD_COND_INITIALIZER;
  15. pthread_cond_t Buffer_Not_Empty=PTHREAD_COND_INITIALIZER;
  16. pthread_mutex_t mVar=PTHREAD_MUTEX_INITIALIZER;
  17.  
  18.  
  19. int wait(int);
  20. int Signal(int);
  21. int main()
  22. {
  23. int n;
  24. pthread_t ptid,ctid;
  25.  
  26. BUFFER=(char *) malloc(sizeof(char) * BufferSize);
  27.  
  28. printf("\n1.Producer\n2.Consumer\n3.Exit");
  29. while(1)
  30. {
  31. printf("\nEnter your choice:");
  32. scanf("%d",&n);
  33. switch(n)
  34. {
  35. case 1: if((mutex==1)&&(empty!=0)){
  36. //producer();
  37. pthread_create(&ptid,NULL,producer,NULL);
  38. pthread_join(ptid,NULL);}
  39. else
  40. printf("Buffer is full!!");
  41. break;
  42. case 2: if((mutex==1)&&(full!=0)){
  43. //consumer();
  44.  
  45. pthread_create(&ctid,NULL,consumer,NULL);
  46. pthread_join(ctid,NULL);}
  47. else
  48. printf("Buffer is empty!!");
  49. break;
  50. case 3:
  51. exit(0);
  52. break;
  53. }
  54. }
  55.  
  56.  
  57.  
  58. return 0;
  59. }
  60.  
  61. int wait(int s)
  62. {
  63. return (--s);
  64. }
  65.  
  66. int Signal(int s)
  67. {
  68. return(++s);
  69. }
  70.  
  71. void *producer()
  72. {
  73. mutex=wait(mutex);
  74. full=Signal(full);
  75. empty=wait(empty);
  76. x++;
  77. printf("\nProducer produces the item %d",x);
  78. mutex=Signal(mutex);
  79. }
  80.  
  81. void *consumer()
  82. {
  83. mutex=wait(mutex);
  84. full=wait(full);
  85. empty=Signal(empty);
  86. printf("\nConsumer consumes item %d",x);
  87. x--;
  88. mutex=Signal(mutex);
  89. }
  90.  

Comments

Popular posts from this blog

Introduction to ChatGPT: Explain what ChatGPT is, how it works, and what it is used for.

Multi Level Inheritance In cpp

Hybrid Inheritance In cpp