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 BUFFER_SIZE 10
  8.  
  9. int buffer[BUFFER_SIZE], counter = 0;
  10.  
  11. sem_t full, empty;
  12. pthread_mutex_t mutex;
  13.  
  14. void write_buffer(int item) {
  15. buffer[counter++] = item;
  16. }
  17.  
  18. int read_buffer() {
  19. return buffer[--counter];
  20. }
  21.  
  22. void* producer(void* param) {
  23. int item = rand() % 100;
  24.  
  25. sem_wait(&empty);
  26. pthread_mutex_lock(&mutex);
  27.  
  28. write_buffer(item);
  29. printf("Producer produced item: %d\n", item);
  30.  
  31. pthread_mutex_unlock(&mutex);
  32. sem_post(&full);
  33.  
  34. return NULL;
  35. }
  36.  
  37. void* consumer(void* param) {
  38. sem_wait(&full);
  39. pthread_mutex_lock(&mutex);
  40.  
  41. int item = read_buffer();
  42. printf("Consumer consumed item: %d\n", item);
  43.  
  44. pthread_mutex_unlock(&mutex);
  45. sem_post(&empty);
  46.  
  47. return NULL;
  48. }
  49.  
  50. int main() {
  51. int n1, n2;
  52.  
  53. pthread_t tidP[20], tidC[20];
  54.  
  55. printf("Enter number of producers: ");
  56. scanf("%d", &n1);
  57. printf("Enter number of consumers: ");
  58. scanf("%d", &n2);
  59.  
  60. sem_init(&full, 0, 0);
  61. sem_init(&empty, 0, BUFFER_SIZE);
  62. pthread_mutex_init(&mutex, NULL);
  63.  
  64. for(int i = 0; i < n1; i++)
  65. pthread_create(&tidP[i], NULL, producer, NULL);
  66.  
  67. for(int i = 0; i < n2; i++)
  68. pthread_create(&tidC[i], NULL, consumer, NULL);
  69.  
  70. for(int i = 0; i < n1; i++)
  71. pthread_join(tidP[i], NULL);
  72.  
  73. for(int i = 0; i < n2; i++)
  74. pthread_join(tidC[i], NULL);
  75.  
  76. sem_destroy(&full);
  77. sem_destroy(&empty);
  78. pthread_mutex_destroy(&mutex);
  79.  
  80.  
  81. }
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
Enter number of producers: Enter number of consumers: