// compile with // g++ -DQT_THREAD_SUPPORT -L$QTDIR/lib -lqt-mt -I$QTDIR/include -o AufzugSim AufzugSim.cpp // #include #include #include #include #include #include #include using namespace std; class Aufzug { // Klasse fuer Aufzug als Singleton private: static Aufzug * instance; int floor; QMutex mutex; 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 : public QThread { 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 ) { QThread::msleep( st ); }; // map to protected QThread msleep virtual void run(); }; // static variable muss extra definiert werden bool AufzugPerson::stop = false; void Aufzug::travel( int stock, int newfloor ) { // Methode zum Fahren int traveltime; mutex.lock(); // start sync traveltime = abs( stock - floor ); // Zur Person fahren AufzugPerson::msleep( traveltime * TIMESCALE ); traveltime = abs( newfloor - stock ); // Zum neuen Stock fahren AufzugPerson::msleep( traveltime * TIMESCALE ); floor = newfloor; mutex.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(); aufz->travel( stock, newstock ); // hol und fahr Aufzug long tused = t.elapsed(); // Zeitmessung cout << "Person " << id << " travelled from " << stock << " to " << newstock << " in " << tused << 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; for ( int i = 0; istart(); // start Person Threads } AufzugPerson::msleep( 1000 * 120 ); // main thread sleep for 2 mins AufzugPerson::stop = true; // stop flag // wait to let them finish properly for ( int i = 0; iwait(); } }