fork download
  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3. #include <chrono>
  4. #include <mutex>
  5.  
  6. using namespace std;
  7.  
  8. class Scheduler{
  9. private:
  10. thread consumer_thread;
  11.  
  12. Scheduler(){
  13. consumer_thread = thread([this](){ this->consumeTasks(); });
  14. }
  15.  
  16. void consumeTasks(){
  17. return;
  18. }
  19. };
  20.  
  21.  
  22. class Bathroom{
  23. private:
  24. int count = 0;
  25. string state = "unset";
  26.  
  27. mutex m;
  28. condition_variable cv;
  29.  
  30. public:
  31. void MaleUseBathroom(string name){
  32. unique_lock<mutex>lock(m);
  33. cv.wait(lock, [this] { return (state == "unset")||(state == "male" && count < 2); });
  34. //critical section
  35. if (state == "unset"){
  36. state = "male";
  37. }
  38. count++;
  39. lock.unlock();
  40.  
  41. this_thread::sleep_for(100ms); //using
  42. cout<<name<<" is using the bathroom"<<endl;
  43.  
  44. lock.lock();
  45. count--;
  46. if (count == 0){
  47. state = "unset";
  48. }
  49. lock.unlock();
  50. cv.notify_all();
  51. }
  52.  
  53. void FemaleUseBathroom(string name){
  54. unique_lock<mutex>lock(m);
  55. cv.wait(lock, [this] { return (state == "unset")||(state == "female" && count < 2) ;});
  56. //critical section
  57. if (state == "unset"){
  58. state = "female";
  59. }
  60. count++;
  61. lock.unlock();
  62.  
  63. this_thread::sleep_for(100ms); //using
  64. cout<<name<<" is using the bathroom"<<endl;
  65.  
  66. lock.lock();
  67. count--;
  68. if (count == 0){
  69. state = "unset";
  70. }
  71. lock.unlock();
  72. cv.notify_all();
  73. }
  74. };
  75.  
  76. void UseBathroom(Bathroom& bathroom, string name, int gender){
  77. if (gender){
  78. bathroom.MaleUseBathroom(name);
  79. }else{
  80. bathroom.FemaleUseBathroom(name);
  81. }
  82. }
  83.  
  84. int main() {
  85. // your code goes here
  86. Bathroom b;
  87. thread t1(UseBathroom, std::ref(b), "atharva", 1);
  88. thread t2(UseBathroom, std::ref(b), "vinda", 0);
  89. thread t3(UseBathroom, std::ref(b), "athar", 1);
  90. thread t4(UseBathroom, std::ref(b), "vind", 0);
  91. thread t5(UseBathroom, std::ref(b), "ath", 1);
  92. thread t6(UseBathroom, std::ref(b), "vin", 0);
  93. thread t7(UseBathroom, std::ref(b), "viku", 0);
  94. thread t8(UseBathroom, std::ref(b), "vikuuk", 0);
  95.  
  96. t1.join();
  97. t2.join();
  98. t3.join();
  99. t4.join();
  100. t5.join();
  101. t6.join();
  102. t7.join();
  103. t8.join();
  104. return 0;
  105. }
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
viku is using the bathroom
vikuuk is using the bathroom
vinda is using the bathroom
vin is using the bathroom
vind is using the bathroom
athar is using the bathroom
ath is using the bathroom
atharva is using the bathroom