码迷,mamicode.com
首页 > 其他好文 > 详细

gen_fsm的学习笔记

时间:2014-12-09 13:41:12      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   on   div   

网上搜索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的学习笔记

标签:style   blog   io   ar   color   sp   for   on   div   

原文地址:http://www.cnblogs.com/ziyouchutuwenwu/p/4152979.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!