[erlang-questions] gen_server and init

Loïc Hoguin <>
Mon Jul 27 16:40:30 CEST 2015


This and sending yourself a message is a bad idea. It will usually work, 
until it doesn't, and you will have a very hard time figuring out why.

Instead, start the process using proc_lib:spawn_link or 
proc_lib:start_link (depending on whether it needs to be synchronous or 
not), then perform your initialization (calling proc_lib:init_ack where 
appropriate), and finally calling gen_server:enter_loop.

What this gives you is pretty much the ability to customize the 
initialization of your gen_server process.

This is the correct way to do it. Your solution can fail if you receive 
a message. Sending yourself a message is subject to race conditions 
where you receive a message before you could init.

On 07/27/2015 04:25 PM, Matthew Evans wrote:
> Hi,
>
> We have used this pattern in gen_servers for a long time now:
>
> init(_) ->
>     %% Some stuff
>     {ok, #state{}, 0}.
>
> %%%
> %%%
>
> handle_info(timeout, State) ->
>      %% Init stuff
>      {noreply,State}
>
> Basically the idea is to prevent init from blocking and to have init/1
> return with a timeout of 0 causing an immediate timeout message to be
> invoked in the handle_info.
>
> Here's what's odd. Sometimes this timeout does not fire. It doesn't
> appear that any message is getting sent, but I would imagine that since
> it's a registered gen_server there is no way that can happen.
>
> Does anyone have any ideas?
>
> We are running vsn 17.1, and ntp is enabled on the host (Linux).
>
> Thanks
>
>
> _______________________________________________
> erlang-questions mailing list
> 
> http://erlang.org/mailman/listinfo/erlang-questions
>

-- 
Loïc Hoguin
http://ninenines.eu
Author of The Erlanger Playbook,
A book about software development using Erlang



More information about the erlang-questions mailing list