Online Search GEN_FSM example, 90% are code_lock, according to gourd painting scoop down, record some learning experience
Init (Unlockcode), Process_flag (trap_exit,true), Io:format (" Init: ~p~n " , [Unlockcode]), {OK, locked, {[], Unlockcode}}.
Init return value inside, Locked is statename,{[], unlockcode} is statedata, useful in callback function
There are two ways of sending an event
gen_fsm:send_event (code_lock, {button, Digit}). gen_fsm:sync_send_event (Code_lock, {button, Digit}, 100000).
The first asynchronous processing is generally used
Asynchronous callback function declaration, StateName (Event, Statedata)
Locked ({button, Digit}, {sofar, unlockcode})Io:format ("Async buttion: ~p, so far: ~p, Code: ~p~n", [Digit, Sofar, Unlockcode]), Inputdigits=lists:append (Sofar, Digit), CaseInputdigits of Unlockcode-Do_unlock (), {next_state, open, {[], unlockcode},10000}; Incomplete when length (incomplete)<length (Unlockcode){next_state, locked, {Digit, unlockcode}, the}; Wrong-Delay:delay (10000000000), Io:format ("wrong passwd: ~p~n", [wrong]), {next_state, locked, {[], unlockcode}} end;
Synchronous callback function declaration, StateName (Event, From,statedata)
Locked ({button, Digit}, _from,{sofar, Unlockcode})Io:format ("sync buttion: ~p, so far: ~p, Code: ~p~n", [Digit, Sofar, Unlockcode]), Inputdigits=lists:append (Sofar, Digit), CaseInputdigits of Unlockcode-Do_unlock (), {next_state, open, {[], unlockcode},10000}; Incomplete when length (incomplete)<length (Unlockcode){next_state, locked, {Digit, unlockcode}, the}; Wrong-Io:format ("wrong passwd: ~p~n", [wrong]), {next_state, locked, {[], unlockcode}} end;
Another, the Erl terminal test to gen_fsm:start_link out of the PID send exit message, handle_info receive, Cancel link received after, processing probably as follows
Handle_info ({' Exit ', Pid,reason}, StateName, Data), Io:format ("Exit ~n"), {stop, statename , Data};
Currently it looks like the process Pool section, with Gen_server as a worker than with GEN_FSM to Simple point, then gen_server it
GEN_FSM's study notes