erlang gen_server 模版

今天终于理解了gen_server行为模式。

这里放一个模版,以方便自己使用:

-module(test8).

-behaviour(gen_server).

-export([start_link/0,stop_link/0]).

-export([init/1,handle_call/3,handle_cast/2,handle_info/2,terminate/2,code_change/3]).

-define(SERVER,?MODULE).

%% 不知道这个state的作用是什么
-record(state,{}).
%% 给外面调用的。

%%% ----------------------------------------------
%%% 公开的API
%%% 
%%% ----------------------------------------------

start_link()->
        gen_server:start_link({local,?SERVER},?MODULE,[],[]).
stop_link()->
        gen_server:cast(?SERVER,stop).

%%% ---------------------------------------------
%%% 私有函数
%%% ---------------------------------------------

%%% -------------------------------------------
%%% 以下是回调函数
%%% -------------------------------------------

%% Result = {ok,State} | {ok,State,Timeout} | {ok,State,hibernate}
%% | {stop,Reason} | ignore
%% 这里设置timeout为0,根据<<erlang并发编程>>描述,可以让init/1尽快结束,是一个众所周知的技巧。
init([])->
        {ok,#state{},0}.

%% Result = {reply,Reply,NewState} | {reply,Reply,NewState,Timeout}
%%  | {reply,Reply,NewState,hibernate}
%%  | {noreply,NewState} | {noreply,NewState,Timeout}
%%  | {noreply,NewState,hibernate}
%%  | {stop,Reason,Reply,NewState} | {stop,Reason,NewState}
handle_call(Request,From,State)->
        Reply=ok,
        {reply,Reply,State}.

%% Result = {noreply,NewState} | {noreply,NewState,Timeout}
%%  | {noreply,NewState,hibernate}
%%  | {stop,Reason,NewState}
handle_cast(Request,State)->
        case Request of
                stop    -> {stop,normal,State};
                _       -> {noreplay,State}
        end.

%% Result = {noreply,NewState} | {noreply,NewState,Timeout}
%%  | {noreply,NewState,hibernate}
%%  | {stop,Reason,NewState}
handle_info(Info,State)->
        {noreply,State}.
terminate(Reason,State)->
        io:format("server is stopped"),
        ok.
code_change(OldVsn,State,Extra)->
        {ok,State}.
发表评论?

0 条评论。

发表评论


注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


Warning: Use of undefined constant XML - assumed 'XML' (this will throw an Error in a future version of PHP) in /opt/wordpress/wp-content/plugins/wp-syntaxhighlighter/wp-syntaxhighlighter.php on line 1048