4
votes

I am new to erlang, I having following code:

-module (test_srv).
-behaviour (gen_server).
-export ([start_link/0, init/1, handle_info/2]).

start_link() ->
  gen_server:start_link(?MODULE, [], []).

init([]) ->
  self() ! asdasd,
  {ok, new_state}.

handle_info(Msg, State) ->
  io:format("server got ~p , now state is ~p~n", [Msg, State]),
  {noreply, State}.

I test in erl shell:

1> {_, P} = test_srv:start_link().
server got asdasd , now state is new_state

The problem is, When send a message to server when the server is not initialised and not readly, how dose gen_server handle the message? I have following guesses:

  1. gen_server handle the message immediately, and send the message to handle_info callback, but will lose initialised state in init callback

  2. gen_server store the message if not server initialised, and send message after server initialised.

I wanna to know how erlang or gen_server handle this problem? what is the principle of handle message?

1

1 Answers

4
votes

I'm guessing by server is not initialised you mean the rest of the init function being executed. In that case your second guess is correct. It's guaranteed that the handle_info will be executed after init has returned. Since the gen_server is a single process, and you're already executing init, the messages sent to itself from init will only be processed by gen_server after init has finished executing.