Single lane bridge problem

If you are not familiar with the problem, this is something like this .

I did not come to ask for an answer, I really finished all my coding. I just found that my solution does not solve it in the best way, because my solution allows only one car at a time on the bridge. I was hoping I could get some tips on how to use sem_wait and sem_post to solve this problem. I hope that the flow going in one direction will flow together, and not one at a time.

My solution currently looks something like this:

(default sem_t north and south = 1 to unlock for 1 car)

IF northcar, then sem_wait (south), sem_wait (north). Cross the bridge and then sem_post (north), sem_post (south). This is obviously wrong because it blocks the bridge from all cars except what’s on it. I want to enable traffic flow. Any ideas?

I use randomly generated traffic, which adds a bit of complexity to it.

+3
source share
2 answers

In real life, you will solve this problem with a traffic light that is either red-north / green-south, green-north / red-south, or red-north / red-south, and the sensors are in the approach and exit lanes at both ends of the bridge.

, -/-. , . , . -, - -. , , ( ), -. , .

, . ( counting .)

+2

- -, . . , , :

function main():
    while(true):
        if(north_car):
            let_north_cars_through()
        if(south_car):
            let_south_cars_through()


function let_south_cars_through():
    sem_wait(north)
    for(i = 0; i < max cars; i++):
        if(south_car):
            cross_bridge()
        else:
            break;

    sem_post(north)

function let_north_cars_through()
    sem_wait(south)
    for(i = 0; i < max cars; i++):
        if(north_car):
            cross_bridge()
        else:
            break;

    sem_post(south)
0

Source: https://habr.com/ru/post/1769002/


All Articles