fork download
  1.  
  2. #include<stdio.h>
  3. #include<pthread.h>
  4. #include<semaphore.h>
  5.  
  6. sem_t empty,full,mutex;
  7. int buffer;
  8.  
  9. void *producer(void *a)
  10. {
  11. sem_wait(&empty);
  12. sem_wait(&mutex);
  13.  
  14. buffer=10;
  15. printf("Produced: %d\n",buffer);
  16.  
  17. sem_post(&mutex);
  18. sem_post(&full);
  19. return NULL;
  20. }
  21.  
  22. void *consumer(void *a)
  23. {
  24. sem_wait(&full);
  25. sem_wait(&mutex);
  26.  
  27. printf("Consumed: %d\n",buffer);
  28.  
  29. sem_post(&mutex);
  30. sem_post(&empty);
  31. return NULL;
  32. }
  33.  
  34. int main()
  35. {
  36. pthread_t p,c;
  37.  
  38. sem_init(&empty,0,1);
  39. sem_init(&full,0,0);
  40. sem_init(&mutex,0,1);
  41.  
  42. pthread_create(&p,NULL,producer,NULL);
  43. pthread_create(&c,NULL,consumer,NULL);
  44.  
  45. pthread_join(p,NULL);
  46. pthread_join(c,NULL);
  47.  
  48. sem_destroy(&empty);
  49. sem_destroy(&full);
  50. sem_destroy(&mutex);
  51. return 0;
  52. }
  53.  
Success #stdin #stdout 0s 544KB
stdin
Standard input is empty
stdout
Produced: 10
Consumed: 10