[erlang-questions] gen_server and init

Matthew Evans mattevans123@REDACTED
Mon Jul 27 16:44:20 CEST 2015


Thanks guys,
I guess I was under the assumption that a process could not even get any messages until init had returned and the pid was registered.

> Date: Mon, 27 Jul 2015 16:40:30 +0200
> From: essen@REDACTED
> To: mattevans123@REDACTED; erlang-questions@REDACTED
> Subject: Re: [erlang-questions] gen_server and init
> 
> 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
> > erlang-questions@REDACTED
> > 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
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20150727/679be998/attachment.htm>


More information about the erlang-questions mailing list