首页 > 代码库 > gen_fsm的学习笔记

gen_fsm的学习笔记

网上搜索gen_fsm的例子,90%都是code_lock,依葫芦画瓢弄了下,记录一些学习心得

 

init(UnLockCode) ->    process_flag(trap_exit,true),    io:format("init: ~p~n", [UnLockCode]),    {ok, locked, {[], UnLockCode}}.

init返回值里面,locked为StateName,{[], UnLockCode}为StateData,在回调函数里面有用

 

发送event有两种方式

gen_fsm:send_event(code_lock, {button, Digit}).gen_fsm:sync_send_event(code_lock, {button, Digit},100000).

一般采用第一个异步处理

 

异步的回调函数声明,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),    case InputDigits of        UnlockCode ->            do_unlock(),            {next_state, open, {[], UnlockCode}, 10000};        Incomplete when length(Incomplete)<length(UnlockCode) ->            {next_state, locked, {Digit, UnlockCode}, 5000};        Wrong ->            delay:delay(10000000000),            io:format("wrong passwd: ~p~n", [Wrong]),            {next_state, locked, {[], UnlockCode}}    end;

 

同步的回调函数声明,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),    case InputDigits of        UnlockCode ->            do_unlock(),            {next_state, open, {[], UnlockCode}, 10000};        Incomplete when length(Incomplete)<length(UnlockCode) ->            {next_state, locked, {Digit, UnlockCode}, 5000};        Wrong ->            io:format("wrong passwd: ~p~n", [Wrong]),            {next_state, locked, {[], UnlockCode}}    end;

 

另,erl终端测试给gen_fsm:start_link出来的Pid发exit消息,handle_info收不到,取消link以后收到,处理大概如下

handle_info({‘EXIT‘,Pid,Reason}, StateName, Data) ->    io:format("exit ~n"),    {stop, StateName, Data};

 

目前看起来进程池部分,用gen_server作为worker比用gen_fsm要简单点,那就gen_server吧

gen_fsm的学习笔记