sandeshMC

producer consumer

Oct 8th, 2014
294
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.07 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<semaphore.h>
  3. #include<pthread.h>
  4. int counter=0;
  5. sem_t S,full,empty;
  6.  
  7. void *producer() {
  8.  
  9. while(1) {
  10.  
  11. sem_wait(&empty);
  12. sem_wait(&S);
  13.  
  14. counter++;
  15. sleep(1);
  16. printf("Counter %d\n",counter);
  17. printf("Produced \n");
  18.  
  19. sem_post(&S);
  20. sem_post(&full);
  21. }
  22. }
  23.  
  24.  
  25. void *consumer() {
  26.  
  27. while(1) {
  28.  
  29. sem_wait(&full);
  30. sem_wait(&S);
  31. counter--;
  32. sleep(2);
  33. printf("Counter %d\n",counter);
  34. printf("Consumed \n");
  35. sem_post(&S);
  36. sem_post(&empty);
  37. }
  38. }
  39.  
  40. main() {
  41. sem_init(&S,1,1);
  42. sem_init(&full,1,0);
  43. sem_init(&empty,1,4);
  44. pthread_t thread1,thread2;
  45. pthread_create(&thread1,NULL,&producer,NULL);
  46. pthread_create(&thread2,NULL,&consumer,NULL);
  47. pthread_join(thread1,NULL);
  48. pthread_join(thread2,NULL);
  49. }
  50.  
  51. /*
  52.  
  53. Counter 1
  54. Produced
  55. Counter 2
  56. Produced
  57. Counter 3
  58. Produced
  59. Counter 4
  60. Produced
  61. Counter 3
  62. Consumed
  63. Counter 2
  64. Consumed
  65. Counter 1
  66. Consumed
  67. Counter 0
  68. Consumed
  69. Counter 1
  70. Produced
  71. Counter 2
  72. Produced
  73. Counter 3
  74. Produced
  75. Counter 4
  76. Produced
  77. Counter 3
  78. Consumed
  79. Counter 2
  80. Consumed
  81. Counter 1
  82. Consumed
  83.  
  84. */
Advertisement
Add Comment
Please, Sign In to add comment