fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <semaphore.h>
  5. #include <unistd.h>
  6.  
  7. #define SIZE 5 // Size of the buffer
  8.  
  9. int buffer[SIZE];
  10. int in = 0, out = 0;
  11.  
  12. sem_t empty, full;
  13. pthread_mutex_t mutex;
  14.  
  15. void* producer(void* arg) {
  16. int item;
  17. for (int i = 0; i < 10; i++) {
  18. item = rand() % 100; // Produce an item
  19.  
  20. sem_wait(&empty); // Decrease empty count
  21. pthread_mutex_lock(&mutex); // Lock the buffer
  22.  
  23. buffer[in] = item;
  24. printf("Producer produced: %d\n", item);
  25. in = (in + 1) % SIZE;
  26.  
  27. pthread_mutex_unlock(&mutex); // Unlock the buffer
  28. sem_post(&full); // Increase full count
  29.  
  30. sleep(1); // Simulate time delay
  31. }
  32. return NULL;
  33. }
  34.  
  35. void* consumer(void* arg) {
  36. int item;
  37. for (int i = 0; i < 10; i++) {
  38. sem_wait(&full); // Decrease full count
  39. pthread_mutex_lock(&mutex); // Lock the buffer
  40.  
  41. item = buffer[out];
  42. printf("Consumer consumed: %d\n", item);
  43. out = (out + 1) % SIZE;
  44.  
  45. pthread_mutex_unlock(&mutex); // Unlock the buffer
  46. sem_post(&empty); // Increase empty count
  47.  
  48. sleep(1); // Simulate time delay
  49. }
  50. return NULL;
  51. }
  52.  
  53. int main() {
  54. pthread_t prod, cons;
  55.  
  56. sem_init(&empty, 0, SIZE); // Initially all slots are empty
  57. sem_init(&full, 0, 0); // No items to consume
  58. pthread_mutex_init(&mutex, NULL);
  59.  
  60. pthread_create(&prod, NULL, producer, NULL);
  61. pthread_create(&cons, NULL, consumer, NULL);
  62.  
  63. pthread_join(prod, NULL);
  64. pthread_join(cons, NULL);
  65.  
  66. sem_destroy(&empty);
  67. sem_destroy(&full);
  68. pthread_mutex_destroy(&mutex);
  69.  
  70. return 0;
  71. }
  72.  
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
Producer produced: 83
Consumer consumed: 83
Producer produced: 86
Consumer consumed: 86
Producer produced: 77
Consumer consumed: 77
Producer produced: 15
Consumer consumed: 15
Producer produced: 93
Consumer consumed: 93
Producer produced: 35
Consumer consumed: 35
Producer produced: 86
Consumer consumed: 86
Producer produced: 92
Consumer consumed: 92
Producer produced: 49
Consumer consumed: 49
Producer produced: 21
Consumer consumed: 21