// compile with // g++ -std=c++0x -pthread -o AufzugSimCpp11 AufzugSimCpp11.cpp // #include #include #include #include #include #include #include #include using namespace std; class Aufzug { // Klasse fuer Aufzug als Singleton private: static Aufzug * instance; int floor; mutex amutex; static const int TIMESCALE = 200; // 0.2 sec Aufzug() : floor(0) {}; // private Konstruktor public: static Aufzug * getInstance() { if(instance==0) { // Lazy instantiation instance = new Aufzug(); } return instance; }; void travel( int stock, int newfloor ); // Methode zum Fahren }; Aufzug * Aufzug::instance = 0; // initialization class AufzugPerson { private: Aufzug *aufz; // Aufzug Objekt int stock; // momentaner Stock int id; // identifier public: static bool stop; // Klassenvariablen static const int NSTOCK = 5; static const int TSLEEP = 10; // (sec) AufzugPerson(int num ) { // Konstruktor id = num; aufz = Aufzug::getInstance(); stock = 0; }; static void msleep( long st ) { std::chrono::milliseconds dura( st ); std::this_thread::sleep_for( dura ); }; // map to protected QThread msleep void run(); }; // static variable muss extra definiert werden bool AufzugPerson::stop = false; void Aufzug::travel( int stock, int newfloor ) { // Methode zum Fahren int traveltime; amutex.lock(); // start sync traveltime = fabs( stock - floor ); // Zur Person fahren AufzugPerson::msleep( traveltime * TIMESCALE ); traveltime = fabs( newfloor - stock ); // Zum neuen Stock fahren AufzugPerson::msleep( traveltime * TIMESCALE ); floor = newfloor; amutex.unlock(); // end sync } void AufzugPerson::run() { while ( ! stop ) { // Endlosschleife bis stop flag gesetzt wird int newstock = (int)(((double)NSTOCK * rand()) / (RAND_MAX+1.0)); // random select naechster Stock // cout << "Person " << id << " travels from " << stock << " to " << newstock << endl; if ( newstock != stock ) { //QTime t; // QTime timer zum Zeitmessen //t.start(); using std::chrono::high_resolution_clock; using std::chrono::milliseconds; auto t0 = high_resolution_clock::now(); aufz->travel( stock, newstock ); // hol und fahr Aufzug //long tused = t.elapsed(); // Zeitmessung auto t1 = high_resolution_clock::now(); milliseconds tused = std::chrono::duration_cast(t1 - t0); cout << "Person " << id << " travelled from " << stock << " to " << newstock << " in " << tused.count() << endl; stock = newstock; } // simuliere Arbeit long sleeptime = (long)(( (double)TSLEEP * rand()) / (RAND_MAX+1.0)); // zufaellige Arbeitszeit msleep( sleeptime * 1000); } } int main() { const int NPERSON = 5; srand( time(NULL) ); // initialize random generator with current time vector al; vector th; for ( int i = 0; i