The principle of FSM for finite state machine and the implementation of Go

Source: Internet
Author: User
Tags abstract definition fsm
This is a creation in Article, where the information may have evolved or changed.

Finite state machines (Finite-state machine, abbreviated FSM) can also be called finite state automata. It must be attached to something, and the state of that thing is limited, and through certain triggering events, it transforms its state. For this reason, finite state machines are mathematical models for describing these finite states and triggering events and switching behavior.

Finite state unit into

The finite state machine has two necessary characteristics, one is discrete, and the other is finite. Based on these two points, most things in the real world cannot be represented by finite state machines because of their complex state.

The elements of a finite state machine model describing things consist of the following:

    • State: The state of a thing, including the initial state and the state after all events have been triggered
    • Event: An event that triggers a state change or remains in its original state
    • Behavior or Transformation (action/transition): The process of performing state transitions
    • Detector (Guard): detects whether a condition to be converted to another State satisfies

Application areas

In addition to the mathematical model applications just introduced, finite state machines have important applications in many different fields, including electrical engineering, linguistics, computer science, philosophy, biology, mathematics, and logic. Finite state machine is attributed to automata theory, and the following theory of automata can be seen in the domain hierarchy diagram, the more complex the concept of the outer layer.


Examples of finite state machines

We will take the most classic fans around for example. If the fan has 4 buttons, respectively, is off, 1, 2 and 3, the off button is responsible for turning off the fan, that is to stop the fan rotation, and 1, 2, 3 can let the fan open, and the fan rotation speed is not the same, the resulting wind is not the same.

At this point we determine the 4 states of the fan, which are closed (Poweroff), 1 gears (1st gear), 2 gears (2nd gear), 3 gears (3rd gear). The Press of 4 buttons can affect the status of the fan. This is illustrated by the state diagram below:


If you can't see it, there's a status transfer table.


In order to make it more intuitive for programmers to understand what the FSM is for, I'll show you the finite state machine for the fan.

The limited state machine in the Go language

Altogether 2 files, Fsm.go is the abstract definition of finite state machine, Main.go is a finite state machine on the fan of the specific state rendering, the code is as follows:

Fsm.gopackage mainimport ("FMT" "Sync") type fsmstate string//Status type Fsmevent string//Thing Piece type Fsmhandler func () fsmstate//processing method and returns the new state//finite state machine type FSM struct {mu sync. Mutex//Exclusive lock State fsmstate//current status handlers Map[fsmstate]m Ap[fsmevent]fsmhandler//Process atlas, each state can be set to a limited number of events, perform a limited number of processing}//get the current state func (F *FSM) getState () fsmstate {return f.state}// Sets the current state of Func (F *FSM) setState (newstate fsmstate) {f.state = newstate}//A state adds an event-handling method func (F *FSM) AddHandler (states Fsmst Ate, event fsmevent, handler Fsmhandler) *fsm {If _, OK: = F.handlers[state];!ok {f.handlers[state] = make (ma P[fsmevent]fsmhandler)} If _, OK: = F.handlers[state][event]; OK {fmt. Printf ("[Warning] State (%s) event (%s)} F.handlers[state][event] = handler return f}//event handler func (F *FSM) Call (event fsmevent) fsmstate {f.mu.lock () defer f.mu.unlock () events: = F.handlerS[f.getstate ()] if events = = Nil {return f.getstate ()} if fn, OK: = Events[event]; OK {oldstate: = F.getstate () f.setstate (FN ()) NewState: = F.getstate () fmt. Println ("state from [", Oldstate, "] to [", NewState, "]")} return F.getstate ()}//instantiate Fsmfunc NEWFSM (initstate fsmstate) * FSM {return &fsm{state:initstate, Handlers:make (Map[fsmstate]map[fsmevent]fsmhandler),}}
Main.gopackage mainimport ("FMT") var (Poweroff = Fsmstate ("off") Firstgear = Fsmstate ("1 gears") S Econdgear = Fsmstate ("2 gears") Thirdgear = Fsmstate ("3 gears") Poweroffevent = Fsmevent ("Press Close button") Firstgearev ent = Fsmevent ("Press 1 button") Secondgearevent = Fsmevent ("Press 2 button") Thirdgearevent = Fsmevent ("Press 3 button") Poweroffhandl ER = Fsmhandler (func () fsmstate {fmt. Println ("fan closed") return Poweroff}) Firstgearhandler = Fsmhandler (func () fsmstate {fmt. Println ("Fan open 1, Breeze Xu!") ") return firstgear}) Secondgearhandler = Fsmhandler (func () fsmstate {fmt. Println ("Fan open 2, Chill! ") return secondgear}) Thirdgearhandler = Fsmhandler (func () fsmstate {fmt. PRINTLN ("The electric fan opens 3, the hairstyle is blown disorderly!") Return thirdgear})//fan type electricfan struct {*fsm}//instanced fan func newelectricfan (initstate fsmstate) *electricfan {return &electricfan{FSM:NEWFSM (initstate),}}//entry function func main () {    Efan: = Newelectricfan (Poweroff)//The initial state is off//off status Efan. AddHandler (Poweroff, Poweroffevent, Poweroffhandler) Efan. AddHandler (Poweroff, Firstgearevent, Firstgearhandler) Efan. AddHandler (Poweroff, Secondgearevent, Secondgearhandler) Efan. AddHandler (Poweroff, Thirdgearevent, Thirdgearhandler)//1-stall status Efan. AddHandler (Firstgear, Poweroffevent, Poweroffhandler) Efan. AddHandler (Firstgear, Firstgearevent, Firstgearhandler) Efan. AddHandler (Firstgear, Secondgearevent, Secondgearhandler) Efan. AddHandler (Firstgear, Thirdgearevent, Thirdgearhandler)//2-stall status Efan. AddHandler (Secondgear, Poweroffevent, Poweroffhandler) Efan. AddHandler (Secondgear, Firstgearevent, Firstgearhandler) Efan. AddHandler (Secondgear, Secondgearevent, Secondgearhandler) Efan. AddHandler (Secondgear, Thirdgearevent, Thirdgearhandler)//3-stall status Efan. AddHandler (Thirdgear, Poweroffevent, Poweroffhandler) Efan. AddHandler (Thirdgear, Firstgearevent, Firstgearhandler) Efan. AddhaNdler (Thirdgear, Secondgearevent, Secondgearhandler) Efan. AddHandler (Thirdgear, Thirdgearevent, Thirdgearhandler)//Start Test status change Efan. Call (thirdgearevent)//Press the 3-efan button. Call (firstgearevent)//Press the 1-efan button. Call (poweroffevent)//press the Close button Efan. Call (secondgearevent)//Press the 2-efan button. Call (poweroffevent)//press the Close button}

return after execution:

电风扇开启3档,发型被吹乱了!状态从 [ 关闭 ] 变成 [ 3档 ]电风扇开启1档,微风徐来!状态从 [ 3档 ] 变成 [ 1档 ]电风扇已关闭状态从 [ 1档 ] 变成 [ 关闭 ]电风扇开启2档,凉飕飕!状态从 [ 关闭 ] 变成 [ 2档 ]电风扇已关闭状态从 [ 2档 ] 变成 [ 关闭 ]
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.