[erlang-questions] newbie: Question on Pragmatic Erlang book example, in OTP Introduction

Russell King <>
Sun Nov 25 19:32:36 CET 2007


I have a question about Pragmatic Erlang book example, in OTP
Introduction-the road to the generic server, pg 295-296.  What
modules' functions and which order are these modules' functions are
called, when you do name_server:add(joe, "at_home") ?

do you call: name_server1::add and then rpc fuction in server3, what
happens after this?

when does name_server1:handle({add, Name, Place}, Dict) get called?

Here is the code:

1> server3:start(name_server, name_server1).
true
2> name_server:add(joe, "at home").
ok


-module(server3).
-export([start/2, rpc/2, swap_code/2]).

start(Name, Mod) ->
   register(Name,
            spawn(fun() -> loop(Name,Mod,Mod:init()) end)).

swap_code(Name, Mod) -> rpc(Name, {swap_code, Mod}).

rpc(Name, Request) ->
   Name ! {self(), Request},
   receive
       {Name, Response} -> Response
   end.

loop(Name, Mod, OldState) ->
   receive
       {From, {swap_code, NewCallBackMod}} ->
           From ! {Name, ack},
           loop(Name, NewCallBackMod, OldState);
       {From, Request} ->
           {Response, NewState} = Mod:handle(Request, OldState),
           From ! {Name, Response},
           loop(Name, Mod, NewState)
   end.


-module(name_server1).
-export([init/0, add/2, whereis/1, handle/2]).
-import(server3, [rpc/2]).

%% client routines
add(Name, Place) -> rpc(name_server, {add, Name, Place}).
whereis(Name)    -> rpc(name_server, {whereis, Name}).

%% callback routines
init() -> dict:new().

handle({add, Name, Place}, Dict) -> {ok, dict:store(Name, Place, Dict)};
handle({whereis, Name}, Dict)    -> {dict:find(Name, Dict), Dict}.

regards,
Russ



More information about the erlang-questions mailing list