首页 > 代码库 > 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的学习笔记
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。