pc_mutex.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. Assignment 5b : Producer and Consumer using Mutex
  3. Name : Rushikesh Mukund Fanse
  4. Roll No : 16
  5. Div : H
  6. */
  7. #include<cstdio>
  8. #include<iostream>
  9. #include<unistd.h>
  10. #include<pthread.h>
  11. #include<cstdlib>
  12. #include<vector>
  13. using namespace std;
  14. pthread_mutex_t mutex;
  15. vector<int> basket;
  16. pthread_cond_t conditional_for_producer,conditional_for_consumer;
  17. int produce_item()
  18. {
  19. sleep(2);
  20. int item=rand()%11;
  21. cout<<"item produced "<<item<<endl;
  22. return item;
  23. }
  24. void consume_item(int item)
  25. {
  26. sleep(2);
  27. basket.pop_back();
  28. cout<<"item consumed "<<item<<endl;
  29. }
  30. void put_into_basket(int item)
  31. {
  32. basket.push_back(item);
  33. }
  34. int get_from_basket()
  35. {
  36. return basket.back();
  37. }
  38. void*producer(void*)
  39. {
  40. int item;
  41. while(true)
  42. {
  43. pthread_mutex_lock(&mutex);
  44. while(basket.size()!=0)
  45. pthread_cond_wait(&conditional_for_producer,&mutex);
  46. item=produce_item();
  47. put_into_basket(item);
  48. pthread_cond_signal(&conditional_for_consumer);
  49. pthread_mutex_unlock(&mutex);
  50. }
  51. }
  52. void*consumer(void*)
  53. {
  54. int item;
  55. while(true)
  56. {
  57. pthread_mutex_lock(&mutex);
  58. while(basket.size()==0)
  59. pthread_cond_wait(&conditional_for_consumer,&mutex);
  60. item=get_from_basket();
  61. consume_item(item);
  62. pthread_cond_signal(&conditional_for_producer);
  63. pthread_mutex_unlock(&mutex);
  64. }
  65. }
  66. int main()
  67. {
  68. pthread_t t1;
  69. pthread_t t2;
  70. pthread_mutex_init(&mutex,NULL);
  71. pthread_cond_init(&conditional_for_producer,NULL);
  72. pthread_cond_init(&conditional_for_consumer,NULL);
  73. pthread_create(&t1,NULL,producer,NULL);
  74. pthread_create(&t2,NULL,consumer,NULL);
  75. pthread_join(t1,NULL);
  76. pthread_join(t2,NULL);
  77. pthread_cond_destroy(&conditional_for_producer);
  78. pthread_cond_destroy(&conditional_for_consumer);
  79. return 0;
  80. }
  81. /*
  82. rishi@rishi-PC:~$ ./a.out
  83. item produced 6
  84. item consumed 6
  85. item produced 10
  86. item consumed 10
  87. item produced 6
  88. item consumed 6
  89. item produced 2
  90. item consumed 2
  91. item produced 1
  92. item consumed 1
  93. item produced 4
  94. item consumed 4
  95. item produced 0
  96. item consumed 0
  97. */