Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Definisati klasu parking koja modeluje parking prostor kapaciteta jednog mesta.
- Ova klasa ima operacije:
- void parking::udji();
- void parking::izadji();
- Automobili koji dolaze na parking su predstavljeni nitima.
- Za ulazak na parking, automobil poziva metodu udji().
- Za izlazak sa parkinga, automobil poziva metodu izadji().
- Automobil se na parkingu zadrzava 3 sekunde.
- Pri ulasku, ukoliko je parking zauzet, automobil mora da saceka da se parking oslobodi.
- */
- #include <iostream>
- #include <thread>
- using namespace std;
- const int N = 5;
- class parking {
- mutex m;
- int br, parking_mjesta;
- condition_variable free;
- public:
- parking(int N) : br(0), parking_mjesta(N) {};
- void udji() {
- unique_lock<mutex> l(m);
- while (br == parking_mjesta) {
- free.wait(l);
- }
- br++;
- }
- void izadji() {
- lock_guard<mutex> l(m);
- free.notify_one();
- br--;
- }
- };
- mutex term_mx;
- void automobil(parking& p) {
- p.udji();
- { lock_guard<mutex> l(term_mx);
- cout << "Automobil " << this_thread::get_id() << " usao na parking." << endl;
- }
- this_thread::sleep_for(chrono::seconds(rand()%3));
- p.izadji();
- { lock_guard<mutex> l(term_mx);
- cout << "Automobil " << this_thread::get_id() << " izasao sa parkinga." << endl;
- }
- }
- const int automobila = 10;
- int main() {
- parking p(N);
- thread t[automobila];
- for (int i=0; i<automobila; i++)
- t[i] = thread(automobil, ref(p));
- for (int i=0; i<automobila; i++)
- t[i].join();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement