erlang - What OTP behaviors should I use for such module? -


i have simple erlang module , want rewrite based on otp principles. can not determine opt template should use.

module's code:

-module(main).  -export([start/0, loop/0]).  start() ->      mypid = spawn(main, loop, []),     register( main, mypid).  loop() ->     receive         [pid, getinfo] -> pid! [self(), welcome],             io:fwrite( "got ~p.~n", [pid] ),             // spawn new process here             loop();         quit -> ok;         x ->             io:fwrite( "got ~p.~n", [ x ] ),             // spawn new process here             loop()     end. 

gen_server fine.

couple things:

  • it bad practice send message
  • messages tuples not lists because not dynamic
  • despite comment, not spawn new process. call loop/0 enters same loop.

gen_server init hold start/0 body. api calls sequence , proxy calls via gen_server handle_calls. spawn new process on function call, add spawn function body of desired handle_call. not use handle_info handle incoming messages -- instead of sending them call gen_server api , 'translate' call gen_server:call or cast. e.g.

start_link() ->     gen_server:start_link({local, ?module}, ?module, [], []).  init(_) ->     {ok, #state{}}  welcome(arg) ->    gen_server:cast(?module, {welcome, arg}).  handle_cast({welcome, arg},_,state) ->   io:format("gen_server pid: ~p~n", [self()]),   spawn(?module, some_fun, [arg]),   {noreply, state}  some_fun(arg) ->   io:format("incoming arguments ~p me: ~p~n",[arg, self()]). 

i have never compiled above, should give idea.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -