笔记七 - gen_fsm

-module(fsmtest).
-behaviour(gen_fsm).
-export([init/1, handle_event/3, handle_sync_event/4, handle_info/3, 
            terminate/3, code_change/4]).

-record(state, {}).
init([]) ->
    {ok, state_name, #state{}}.

handle_event(Event, StateName, StateData) ->
    {next_state, StateName, StateData}.

handle_sync_event(Event, From, StateName, StateData) ->
    Reply = ok,
    {reply, Reply, StateName, StateData}.

handle_info(Info, StateName, StateData) ->
    {next_state, StateName, StateData}.

terminate(Reason, StateName, StatData) ->
    ok.

code_change(OldVsn, StateName, StateData, Extra) ->
    {ok, StateName, StateData}.

gen_fsm这个接口函数和以前的又很相似.首先这次我们需要搞懂一个东西,是什么就是这个gen_fsm中fsm是什么东东,之前几个都是全名称,很好理解,一看就明白.
fsm就是Finite State Machines的缩写.知道全称后就明白这个模块到底是干什么的了,原来是状态机,而且是叫有限状态机.

开始函数介绍:

init/1 : 同样gen_fsm:start或者gen_fsm:start_link来启动后自动回调该函数.
handle_event/3 : gen_fsm:send_event/send_all_state_event驱动.
handle_sync_event/4 :  gen_fsm: sync_send_event/sync_send_all_state_event驱动. 
handle_info/3 : 这个系统内部消息驱动,或者消息过来,比如send !.具体怎么个法,需深入.
terminate/3 : 当进程被终止时驱动.
code_change/4 : 当代码热更新时被驱动.

handle_event/3和handle_sync_event/4什么区别?好象是后者有返回值.

你可能感兴趣的:(erlang,gen_fsm)