[Tutor] what's a state machine?

Alan Gauld alan.gauld@blueyonder.co.uk
Wed Aug 6 18:09:01 EDT 2003


Kirk wrote a fine description of state machine theory...

> THAT is a turing machine. It is a complete computer, and can compute
> ANYTHING. Eventually. If you do not go insane first.
>
> And is a complete pain in the ass.

To which I add that while Turing complete state machines are
hard dedicated purpose state machines are both very easy to
build, easy to maintain and extremely performant. This is
the reason why most large scale real-time systems are built
as state machines. Its also why a complete methodology and
notation exists to document such machines - its called SDL
- The Specification and Design Language, and is used to design
almost all modern telephone exchanges, air-traffic control
systems, railway control systems, factory control etc etc.

The secret is to model the machine as a big table:

Current State|Event|Action|Next State

You then define numeric values(or hash keys) for each state
and each event, load pointers/rferences to functions into
the action column and set of a loop that looks something
like this:

while True:
   EventID = getEvent()  # figure out how to get the events!
   try:
      StateTable[myState][EventID].Action()
      myState = StateTable[myState][EventID].nextState
   except:  # handle an error

Another strategy is that the Action should return nextState
but that prevents you from reusing action functions...

Now adding states, events or actions becomes a relatively simple
table build issue. And that can be done from a text file at startup...

Alan G.





More information about the Tutor mailing list