//------------------------------------------------------------------------ // Filename: // bridge-Thrd.cpp // PROGRAM DESCRIPTION // Implementation of vehicle threads //------------------------------------------------------------------------ #include #include "ThreadClass.h" #include "bridge-Thrd.h" #include "bridge-mon.h" // static data variables static BridgeMonitor Bridge("Bridge"); // ------------------------------------------------------------------- // FUNCTION Filler(): // This function fills a char array with spaces. // ------------------------------------------------------------------- void Filler(char x[], int n) { int i; for (i = 0; i < n*2; i++) x[i] = ' '; x[i] = '\0'; } //------------------------------------------------------------------------ // Vehicle::Vehicle() // constructor for Vehicle class //------------------------------------------------------------------------ Vehicle::Vehicle(int id, int max_run) { ID = id; Max_Run = max_run; ThreadName.seekp(0, ios::beg); ThreadName << "Vehicle" << id << '\0'; } // ------------------------------------------------------------------- // Vehicle::ThreadFunc() // This function simulates a vehicle crossing the bridge. // ------------------------------------------------------------------- void Vehicle::ThreadFunc() { Thread::ThreadFunc(); int Direction; char *Dir[2] = { "<--", "-->" }; char space[200]; int i; Filler(space, ID); cout << space << ThreadName.str() << " started ..." << endl; for (i = 1; i <= Max_Run; i++) { // for each crossing Delay(); // rest for a while Direction = rand() % 2; // a random direction cout << space << ThreadName.str() << "(" << i << ") arrives at the bridge in direction " << Dir[Direction] << endl; Bridge.ArriveBridge(Direction); // arrive at the bridge cout << space << ThreadName.str() << "(" << i << ") crosses the bridge" << endl; Delay(); // crossing the bridge Bridge.ExitBridge(Direction); // exit the bridge cout << space << ThreadName.str() << "(" << i << ") is done" << endl; } cout << space << ThreadName.str() << " is gone forever ..." << endl; Exit(); } // end of bridge-Thrd.cpp