General Design Question
I have a general design question: T开发者_Go百科here is a junction, with four roads connecting to it. Each road has 2 lanes. What would be the best way to design a program to handle such junction. It should allow 2 cars 2 go through the junction if they don't interfere each other. and 1 car came in before the other, and they both should use the same part of the junction, the 1st car should get priority. Also, 2 cars may arrive the junction at the exact same time. What would be the best design for this problem? what exactly should you lock, in order to allow best use of the junction?
Thanks!
Each car should lock parts of the lane it's going to pass trough. If one of the parts is locked then car should wait until it will be released.
What do you think about having 4 different queues for each part of the junction. each car that comes in enters the relevant queue (should enter to more than one queue?), and only after the car leaves all queue it can go through the junction.. Still not sure what is the best implementation for it though.
Create a circle buffer with two entries for each road (one for inbound, one for outbound) meeting at the intersection.
For each car that you have to route put it's name into the circle buffer for its source (inbound) and its destination (outbound). Then iterate through the circle buffer, if you get two instances of the same car together then that car may travel. After that pick at random from the other cars.
I have a feeling that's pretty unclear so consider an intersection with 4 roads that we'll call N, E, S and W. To that we'll have 3 cars, A coming from the East turning South, B from the South travelling North and C from the West travelling East.
Circle buffer can be built as such (i=inbound, o=outbound:
Ni No Ei Eo Si So Wi Wo
B - C A A B - C
As we iterate through from left to right we realise that the two A's are adjacent so they can go but the B's and C's are not adjacent so these cars are block each other. Pick one at random for this light cycle and let the other go in the next light cycle. So either A and B can go or A and C can go.
Note1: testing adjacent ignores blanks so in the case of
Ni No Ei Eo Si So Wi Wo
D E - - E D - -
which models a car travelling North and another travelling South both E's and D's are adjacent.
Note2: I've mapped this out for driving on the left because that's what I do. You'll have to mirror it for driving on the right.
Note3: You can't overwrite a position in the buffer, if two cars want the same destination they're automatically blocking and you should just leave the first one in there and consider the other one next time.
精彩评论