Advertisement
Guest User

Untitled

a guest
Apr 30th, 2016
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <semaphore.h>
  5. #include <unistd.h>
  6. sem_t barber,customer,mutex;
  7. int count=0;
  8. void *GetHairCut(){
  9. while(1){
  10. if(count==0){
  11. //barber will be sleeping as the count is zero means
  12. //there is noo customer currently in the shop for hair cut
  13. sem_wait(&barber);
  14. sem_wait(&mutex);
  15.  
  16. //now when the customer will come he will wake up the barber
  17. //to ger a hair cut
  18. sem_post(&mutex);
  19. sem_post(&barber);
  20. }
  21. if(count==3){
  22. //as we can have max of 3 customer in waiting so this check will
  23. //make sure that not more then 3 customer are waiting
  24. printf("Note:No more space for more customer/waiting room is full.\n");
  25. break;
  26. }
  27. else{
  28. //this check will increment the customer who are commin into the shop while
  29. //the barber is cutting the hair of the customer
  30. count++;
  31. printf("customer count in waiting:%d\n",count-1);
  32. }
  33. }
  34.  
  35. }
  36.  
  37. void *CutHair(){
  38. while(1){
  39. if(count>0){
  40. //cutting the hair of the customer
  41. sem_wait(&mutex);
  42. //will take one customer into the critical sention and put lock
  43. //only one persons hair cut at one time
  44. sem_wait(&customer);
  45. //decrement means that barber is done with one customer
  46. count--;
  47. printf("customer count in waiting:%d\n",count);
  48.  
  49. //will unlock the critical section after providing the hair to a single
  50. //customer
  51. sem_post(&customer);
  52. sem_post(&mutex);
  53. }
  54. else{
  55. printf("Note:No more customer available.\n");
  56. break;
  57. }
  58. }
  59. }
  60. int main(){
  61. sem_init(&mutex,0,1);
  62. sem_init(&barber,0,1);
  63. sem_init(&customer,0,1);
  64. pthread_t thread1,thread2;
  65. pthread_create(&thread1,NULL,GetHairCut,NULL);
  66. pthread_create(&thread2,NULL,CutHair,NULL);
  67.  
  68. pthread_join(thread1,NULL);
  69. pthread_join(thread2,NULL);
  70.  
  71. sem_destroy(&mutex);
  72. sem_destroy(&barber);
  73. sem_destroy(&customer);
  74. }
  75.  
  76. Record Page AdsClose
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement