Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <thread>
- using namespace std;
- mutex m;
- class parking{
- bool zauzet;
- condition_variable ulazi[2];
- int na_redu;
- public:
- parking():zauzet(false),na_redu(0){}
- void udji(int ulaz);
- void izadji();
- };
- void parking::udji(int ulaz){
- unique_lock<mutex> lock(m);
- while (zauzet){
- if(ulaz==0)
- ulazi[0].wait(lock);
- else
- ulazi[1].wait(lock);
- }
- zauzet=true;
- na_redu=(na_redu+1)%2;
- cout<<"Automobil sa registracijom "<<this_thread::get_id()<<" sa ulaza"<<ulaz<<" usao je na parking"<<endl;
- }
- void parking::izadji(){
- zauzet=false;
- ulazi[na_redu].notify_one();
- }
- void automobil (parking &p,int ulaz,int ostajem_na_parkingu){
- // {
- // lock_guard<mutex> lock(m);
- // cout<<"Automobil sa registracijom "<<this_thread::get_id()<<" sa ulaza"<<ulaz<<" zeli da udje na parking"<<endl;
- //}
- p.udji(ulaz);
- this_thread::sleep_for(chrono::seconds(ostajem_na_parkingu));
- p.izadji();
- lock_guard<mutex> lock(m);
- cout<<"Automobil sa registracijom "<<this_thread::get_id()<<" sa ulaza"<<ulaz<<" je izasao sa parkinga"<<endl;
- }
- int main()
- {
- thread t[10];
- parking p;
- for (int i=0;i<5;i++)
- t[i]=thread(automobil,ref(p),0,1);
- for (int i=5;i<10;i++)
- t[i]=thread(automobil,ref(p),1,3);
- for (int i=0;i<10;i++)
- t[i].join();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement