fork download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<pthread.h>
  4. #include<semaphore.h>
  5.  
  6. #define n 10
  7.  
  8. typedef sem_t semaphore;
  9. semaphore s;
  10. semaphore full;
  11. semaphore empty;
  12. int in = 0;
  13. int out = 0;
  14. int buffer[n] = {0};
  15. int max_items = 10;
  16.  
  17. int produce_item()
  18. {
  19. return rand()%100;
  20. }
  21.  
  22. void insert_item(int item)
  23. {
  24. buffer[in] = item;
  25. in = (in+1)%n;
  26. }
  27.  
  28. int remove_item()
  29. {
  30. int item = buffer[out];
  31. out = (out+1)%n;
  32. return item;
  33. }
  34.  
  35. void* producer(void* arg)
  36. {
  37. for(int i=0;i<max_items;i++)
  38. {
  39. int item = produce_item();
  40. sem_wait(&empty);
  41. sem_wait(&s);
  42. insert_item(item);
  43. printf("Produced item : %d\n",item);
  44. sem_post(&full);
  45. sem_post(&s);
  46. }
  47. }
  48.  
  49. void* consumer(void* arg)
  50. {
  51. for(int i=0;i<max_items;i++)
  52. {
  53. sem_wait(&full);
  54. sem_wait(&s);
  55. int item = remove_item();
  56. printf("Consumed item : %d\n",item);
  57. sem_post(&s);
  58. sem_post(&empty);
  59. }
  60. }
  61.  
  62. int main()
  63. {
  64. pthread_t pro,con;
  65.  
  66. sem_init(&s,0,1);
  67. sem_init(&full,0,0);
  68. sem_init(&empty,0,n);
  69.  
  70. pthread_create(&pro,NULL,producer,NULL);
  71. pthread_create(&con,NULL,consumer,NULL);
  72.  
  73. pthread_join(pro,NULL);
  74. pthread_join(con,NULL);
  75.  
  76. sem_destroy(&s);
  77. sem_destroy(&full);
  78. sem_destroy(&empty);
  79.  
  80. return 0;
  81. }
Success #stdin #stdout 0.01s 5272KB
stdin
Standard input is empty
stdout
Produced item : 83
Produced item : 86
Produced item : 77
Produced item : 15
Produced item : 93
Produced item : 35
Produced item : 86
Produced item : 92
Produced item : 49
Produced item : 21
Consumed item : 83
Consumed item : 86
Consumed item : 77
Consumed item : 15
Consumed item : 93
Consumed item : 35
Consumed item : 86
Consumed item : 92
Consumed item : 49
Consumed item : 21