fork download
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <semaphore.h>
  4. #include <unistd.h>
  5.  
  6. #define BUFFER_SIZE 5
  7. #define NUM_ITEMS 10
  8.  
  9. int buffer[BUFFER_SIZE];
  10. int in = 0, out = 0;
  11.  
  12. sem_t empty_slots, full_slots, mutex;
  13.  
  14. void *producer(void *arg) {
  15. int item;
  16. for (int i = 0; i < NUM_ITEMS; i++) {
  17. item = i;
  18. sem_wait(&empty_slots);
  19. sem_wait(&mutex);
  20.  
  21. buffer[in] = item;
  22. printf("Produced %d\n", item);
  23. in = (in + 1) % BUFFER_SIZE;
  24.  
  25. sem_post(&mutex);
  26. sem_post(&full_slots);
  27. usleep(200000); // Sleep to simulate production time
  28. }
  29. pthread_exit(NULL);
  30. }
  31.  
  32. void *consumer(void *arg) {
  33. int item;
  34. for (int i = 0; i < NUM_ITEMS; i++) {
  35. sem_wait(&full_slots);
  36. sem_wait(&mutex);
  37.  
  38. item = buffer[out];
  39. printf("Consumed %d\n", item);
  40. out = (out + 1) % BUFFER_SIZE;
  41.  
  42. sem_post(&mutex);
  43. sem_post(&empty_slots);
  44. usleep(500000); // Sleep to simulate consumption time
  45. }
  46. pthread_exit(NULL);
  47. }
  48.  
  49. int main() {
  50. pthread_t producer_thread, consumer_thread;
  51.  
  52. sem_init(&empty_slots, 0, BUFFER_SIZE);
  53. sem_init(&full_slots, 0, 0);
  54. sem_init(&mutex, 0, 1);
  55.  
  56. pthread_create(&producer_thread, NULL, producer, NULL);
  57. pthread_create(&consumer_thread, NULL, consumer, NULL);
  58.  
  59. pthread_join(producer_thread, NULL);
  60. pthread_join(consumer_thread, NULL);
  61.  
  62. sem_destroy(&empty_slots);
  63. sem_destroy(&full_slots);
  64. sem_destroy(&mutex);
  65.  
  66. return 0;
  67. }
  68.  
Success #stdin #stdout 0s 5304KB
stdin
Standard input is empty
stdout
Produced 0
Consumed 0
Produced 1
Produced 2
Consumed 1
Produced 3
Produced 4
Consumed 2
Produced 5
Produced 6
Produced 7
Consumed 3
Produced 8
Consumed 4
Produced 9
Consumed 5
Consumed 6
Consumed 7
Consumed 8
Consumed 9