Sri27119

producer

Nov 25th, 2024
14
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int mutex = 1;
  5. int full = 0;
  6. int empty, x = 0;
  7.  
  8. void producer() {
  9. --mutex;
  10. ++full;
  11. --empty;
  12. x++;
  13. printf("Producer produces item %d\n", x);
  14. ++mutex;
  15. }
  16.  
  17. void consumer() {
  18. --mutex;
  19. --full;
  20. ++empty;
  21. printf("Consumer consumes item %d\n", x);
  22. x--;
  23. ++mutex;
  24. }
  25.  
  26. void showBuffer() {
  27. printf("\nBuffer Status:");
  28. printf("\nFull slots: %d", full);
  29. printf("\nEmpty slots: %d", empty);
  30. printf("\nTotal items in buffer: %d\n", x);
  31. }
  32.  
  33. int main() {
  34. int n, bufferSize;
  35.  
  36. printf("Enter buffer size: ");
  37. scanf("%d", &bufferSize);
  38.  
  39. empty = bufferSize;
  40.  
  41. printf("\n1. Press 1 for Producer"
  42. "\n2. Press 2 for Consumer"
  43. "\n3. Press 3 for Exit"
  44. "\n4. Press 4 to Show Buffer Status");
  45.  
  46. while (1) {
  47. printf("\nEnter your choice: ");
  48. scanf("%d", &n);
  49.  
  50. switch (n) {
  51. case 1:
  52. if (mutex == 1 && empty != 0) {
  53. producer();
  54. } else {
  55. printf("Buffer is full!\n");
  56. }
  57. break;
  58.  
  59. case 2:
  60. if (mutex == 1 && full != 0) {
  61. consumer();
  62. } else {
  63. printf("Buffer is empty!\n");
  64. }
  65. break;
  66.  
  67. case 3:
  68. exit(0);
  69. break;
  70.  
  71. case 4:
  72. showBuffer();
  73. break;
  74.  
  75. default:
  76. printf("Invalid choice! Please try again.");
  77. }
  78. }
  79. }
  80.  
Add Comment
Please, Sign In to add comment