In: Computer Science
There is a single-plank bridge. Only one person can cross the
bridge without any stop. The pedestrian can cross the bridge from
west to east or from east to west. If there is more than 0
pedestrian crossing the bridge from west to east, no pedestrian can
try to cross the bridge from east to west, but more than 1
pedestrian can cross the bridge from west to east, and vice versa.
The pedestrian can cross the bridge immediately if there is no
pedestrian on the bridge. Use Semaphore to solve this
problem.
To the above problem one solution can be to block one way and let a limited number cars through:
1. It uses a simple variable max to allow maximum number of pedestrain to cross from WtoE or EtoW.
Below is the pseudo code for such a system being implemented using semaphore :
max = 10 // setting car limits
function main():
while(true):
if(westToEast):
let_west_to_east()
if(eastToWest):
let_east_to_west()
function let_east_to_west():
sem_wait(westToEast) // Waiting for west to east direction
for(i = 0; i < max; i++):
if(east):
cross_bridge()
else:
break; // limit cross max reached
sem_post(westToEast) // let west to east go
function let_west_to_east()
sem_wait(eastToWest) // Waiting for east to west direction
for(i = 0; i < max; i++):
if(west):
cross_bridge()
else:
break;
sem_post(eastToWest) // let east to west go