#define MAX_CARS 3 #define EAST 0 #define WEST 1 #define ANY 2 #include #include "synch.h" /* The following procedures are protected by a monitor */ Lock *mylock = new Lock("amylock"); int currentDirection = ANY; // the flow of traffic on the bridge int cars = 0; // The number of cars on the bridge int waiters = 0; // cars waiting for space on the bridge Condition* lessThanMax = new Condition ("max"); Condition* directionChange = new Condition ("change"); char* strings[2] = {"East","West"}; void CrossBridge (int myDirection) { cout << "Crossing the bridge" << endl; } void ArriveBridge (int myDirection) { mylock->Acquire(); while (currentDirection != myDirection && currentDirection != ANY) { directionChange->Wait(mylock); } if (currentDirection != myDirection) { currentDirection = myDirection; cout << "Changed direction to: " << strings[myDirection] << endl; } while (cars == MAX_CARS) { waiters++; lessThanMax->Wait(mylock); waiters--; } cars++; cout << "Car crossing from the " << strings[myDirection] << endl; mylock->Release(); } void ExitBridge (int myDirection) { mylock->Acquire(); cout << "Car leaving from the " << strings[myDirection] << endl; cars--; lessThanMax->Signal(mylock); if (cars == 0 && waiters == 0) { currentDirection = ANY; directionChange->Broadcast(mylock); } mylock->Release(); }