#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) { printf("Crossing the bridge"); } void ArriveBridge (int myDirection) { mylock->Acquire(); while (currentDirection != myDirection && currentDirection != ANY) { directionChange->Wait(mylock); } if (currentDirection != myDirection) { currentDirection = myDirection; printf("Changed direction to: %s\n", strings[myDirection]); } while (cars == MAX_CARS) { waiters++; lessThanMax->Wait(mylock); waiters--; } cars++; printf("Car crossing from the %s\n", strings[myDirection]); mylock->Release(); } void ExitBridge (int myDirection) { mylock->Acquire(); printf("Car leaving from the %s\n", strings[myDirection]); cars--; lessThanMax->Signal(mylock); if (cars == 0 && waiters == 0) { currentDirection = ANY; directionChange->Broadcast(mylock); } mylock->Release(); }