Avoiding Deadlocks

Early on in the development of the system, I kept getting deadlocks.   A deadlock is when two trains end up head-to-head, and neither can continue on it's route.

I had to develop a number of strategies to stop these happening, so the system can keep working indefinitely without any human intervention

Strategy - One way Track
Lots of pieces of the track are now one-way.  This is simple, effective, and mirrors a lot of track in the real world.   When things are one-way, you can never end up with a head-to-head deadlock.  Without this, you would find both mainlines approaching my terminus station being blocked with trains headed in the same direction.

Strategy - Blocks
Another real world strategy - to group a number of pieces into a block.  The block is then locked by a single train and others cannot enter.  Typically most of the points on entry/exit of my terminus stations are grouped into a single block

Strategy - Clear Locks on Stop
When a train is driving it "looks ahead" to anticipate what's coming up next.   This means it can always stop in time, because it can work out speed limits based on looking ahead.  As well as looking ahead, it locks the track ahead and sets points in the correct direction.   However sometimes this could lead to a deadlock - one train wants to enter, one train wants to exit - they both end up with track locked half way, both move as far forward as they can, and both come to a stop.  Special logic comes in when the train fully stops - it will clear all ahead locks, wait a random number of seconds, and wait to see if another train can make better use of the locked track and move.

Strategy - Waiting Lists & Prioritisation
During some of the running sessions I kept noticing that for some reason a train would be waiting trying to exit the terminus station for a long time.  The random unlocking strategy above seemed to not work too well at giving fair prioritisation.   So I developed the waiting list on a block.  This is "first in first out" principle, but it always prioritises arrivals.   So - three trains waiting to exit, they will exit in the order they asked for the block.  If a train arrives, it jumps the list and comes straight in.  If all platforms are full, it will wait until a departure.

Together these strategies work!

Comments