fork download
  1. #include <stdio.h>
  2. #include <semaphore.h>
  3. #include <pthread.h>
  4.  
  5. #define BUFFER_SIZE 100 // Adjust buffer size as needed
  6.  
  7. sem_t mutex, full, empty;
  8. int buff[BUFFER_SIZE];
  9. int in = 0, out = 0; // Indexes for producer and consumer
  10.  
  11. void producer(void *arg) {
  12. int item;
  13. while (1) {
  14. printf("Enter the item to be produced (or -1 to exit): ");
  15. if (scanf("%d", &item) != 1 || item == -1) {
  16. break; // Exit producer if user enters -1 or input error
  17. }
  18.  
  19. sem_wait(&empty); // Wait if buffer is full
  20. sem_wait(&mutex); // Enter critical section
  21.  
  22. // Critical section: Add item to buffer
  23. buff[in] = item;
  24. printf("Item %d stored in buffer\n", buff[in]);
  25. in = (in + 1) % BUFFER_SIZE; // Circular buffer logic
  26.  
  27. sem_post(&mutex); // Exit critical section
  28. sem_post(&full); // Signal a full slot
  29. }
  30. }
  31.  
  32. void consumer(void *arg) {
  33. int item;
  34. while (1) {
  35. sem_wait(&full); // Wait if buffer is empty
  36. sem_wait(&mutex); // Enter critical section
  37.  
  38. // Critical section: Remove item from buffer
  39. item = buff[out];
  40. printf("Item %d consumed from buffer\n", item);
  41. out = (out + 1) % BUFFER_SIZE; // Circular buffer logic
  42.  
  43. sem_post(&mutex); // Exit critical section
  44. sem_post(&empty); // Signal an empty slot
  45. }
  46. }
  47.  
  48. int main() {
  49. int m, n; // Number of producers and consumers
  50.  
  51. printf("Enter the number of producers: ");
  52. scanf("%d", &m);
  53. printf("Enter the number of consumers: ");
  54. scanf("%d", &n);
  55.  
  56. // Semaphore initialization (corrected initialization values)
  57. sem_init(&mutex, 0, 1);
  58. sem_init(&full, 0, 0); // Initially no full slots
  59. sem_init(&empty, 0, BUFFER_SIZE); // Initially all slots empty
  60.  
  61. // Thread creation
  62. pthread_t producers[m], consumers[n];
  63. for (int i = 0; i < m; i++) {
  64. pthread_create(&producers[i], NULL, producer, NULL);
  65. }
  66. for (int i = 0; i < n; i++) {
  67. pthread_create(&consumers[i], NULL, consumer, NULL);
  68. }
  69.  
  70. // Wait for threads to finish
  71. for (int i = 0; i < m; i++) {
  72. pthread_join(producers[i], NULL);
  73. }
  74. for (int i = 0; i < n; i++) {
  75. pthread_join(consumers[i], NULL);
  76. }
  77.  
  78. printf("All producers and consumers finished.\n");
  79. return 0;
  80. }
  81.  
Success #stdin #stdout 0.01s 5316KB
stdin
Standard input is empty
stdout
Enter the number of producers: Enter the number of consumers: All producers and consumers finished.