Erlang gen_server进程调用实例

刚才又重新 理解Gen_server才明白它的工作原理。

handle_call : 是进程之间的调用.. 需要返回值

gen_server完全写好一套消息框架,只需要实现它的功能函数既可。

-module(test_A).

-behaviour(gen_server).

%%External exports
-export([start_link/0,handleCall/1]).

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

-record(state, {}).

%% ====================================================================
%% Server functions
%% ====================================================================

init([]) ->
	process_flag(trap_exit, true),
    {ok, #state{}}.

handle_call({first,Data},_From,State)->
	io:format("recv call backMSG~p~n",[_From]),
	{reply,Data,State};
handle_call(_Request,_From,State)->
	Reply = ok,
	io:format("call recv = ~p~n", Reply),
	{reply,Reply,State}.
	
handle_cast(Msg, State) ->
    {noreply, State}.
	
handle_info(Info, State) ->
    {noreply, State}.
	
terminate(Reason, State) ->
    ok.
	
code_change(OldVsn, State, Extra) ->
    {ok, State}.

%% ====================================================================
%% Server functions
%% ====================================================================
start_link()->
	gen_server:start_link({local, ?MODULE},?MODULE, [], []).
	
handleCall(PID)->
	Name = gen_server:call(PID,{first,"Lee"}),
	io:format("名字是~p~n",[Name]).
	
	

-module(test_B).

-behaviour(gen_server).

%%External exports
-export([start_link/0]).

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

-record(state, {}).

%% ====================================================================
%% Server functions
%% ====================================================================

init([]) ->
	process_flag(trap_exit, true),
    {ok, #state{}}.

handle_call({first,Data},_From,State)->
	io:format("recv From= ~p~n", [_From]),
	{reply,Data,State};
handle_call(_Request,_From,State)->
	Reply = ok,
	{reply,Reply,State}.
	
handle_cast(Msg, State) ->
    {noreply, State}.
	
handle_info(Info, State) ->
	io:format("recv = ~p~n", [Info]),
    {noreply, State}.
	
terminate(Reason, State) ->
    ok.
	
code_change(OldVsn, State, Extra) ->
    {ok, State}.

%% ====================================================================
%% Server functions
%% ====================================================================
start_link()->
	gen_server:start_link({local, ?MODULE},?MODULE, [], []).
	


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值