Advertisement
Guest User

Untitled

a guest
Aug 17th, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. using namespace std;
  4.  
  5. mutex m;
  6.  
  7. class parking{
  8.  
  9. bool zauzet;
  10. condition_variable ulazi[2];
  11. int na_redu;
  12.  
  13.  
  14. public:
  15. parking():zauzet(false),na_redu(0){}
  16. void udji(int ulaz);
  17. void izadji();
  18.  
  19. };
  20.  
  21. void parking::udji(int ulaz){
  22. unique_lock<mutex> lock(m);
  23. while (zauzet){
  24. if(ulaz==0)
  25. ulazi[0].wait(lock);
  26. else
  27. ulazi[1].wait(lock);
  28.  
  29. }
  30. zauzet=true;
  31. na_redu=(na_redu+1)%2;
  32.  
  33.  
  34. cout<<"Automobil sa registracijom "<<this_thread::get_id()<<" sa ulaza"<<ulaz<<" usao je na parking"<<endl;
  35.  
  36. }
  37.  
  38. void parking::izadji(){
  39.  
  40. zauzet=false;
  41. ulazi[na_redu].notify_one();
  42. }
  43.  
  44.  
  45. void automobil (parking &p,int ulaz,int ostajem_na_parkingu){
  46.  
  47. // {
  48. // lock_guard<mutex> lock(m);
  49. // cout<<"Automobil sa registracijom "<<this_thread::get_id()<<" sa ulaza"<<ulaz<<" zeli da udje na parking"<<endl;
  50. //}
  51.  
  52. p.udji(ulaz);
  53.  
  54. this_thread::sleep_for(chrono::seconds(ostajem_na_parkingu));
  55.  
  56. p.izadji();
  57.  
  58. lock_guard<mutex> lock(m);
  59. cout<<"Automobil sa registracijom "<<this_thread::get_id()<<" sa ulaza"<<ulaz<<" je izasao sa parkinga"<<endl;
  60. }
  61.  
  62. int main()
  63. {
  64. thread t[10];
  65. parking p;
  66.  
  67. for (int i=0;i<5;i++)
  68. t[i]=thread(automobil,ref(p),0,1);
  69. for (int i=5;i<10;i++)
  70. t[i]=thread(automobil,ref(p),1,3);
  71. for (int i=0;i<10;i++)
  72. t[i].join();
  73.  
  74. return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement