[erlang-questions] Erlang way for process-as-library?

Mats Cronqvist mats.cronqvist@REDACTED
Wed Feb 7 17:26:49 CET 2007


Hakan Mattsson wrote:
> On Wed, 7 Feb 2007, Mats Cronqvist wrote:
> 
> MC> > Ok it is not safe in that particular regard if the pid
> MC> > really is intended to be used, but as Tobbe did not use
> MC> > in his example I assumed that that it was not intended
> MC> > to be used. 
> MC> 
> MC>    i think it's clear from tobbes code that he intended
> MC> it to return the correct pid. and i think it should.
> 
> Feel free to think so... ;-)

    perhaps we can agree on this; if it does return a pid, it should be the 
right one...

> MC> > If it is important that the correct pid
> MC> > is returned you will need to change the example to:
> MC> >   start() ->
> MC> >     case whereis(my_service) of
> MC> >       Pid when pid(Pid) ->
> MC> >         Pid
> MC> >       _ ->
> MC> >         spawn(my_mod, my_server, []), 
> MC> >         whereis(my_service)
> MC> >     end.
> MC> 
> MC>    the second whereis/1 will (likely) run before the
> MC> register/2 call (presumably present) in my_mod:my_server/0,
> MC> and so will return undefined.
> 
> I did not think about that race condition. It
> definitely complicates things a bit. Perhaps,
> it is time to dust off my good old service_broker
> user contribution. It solved that problem.

   it is a pretty hard problem to solve elegantly. here's what i use. it has at 
least one race condition :>

   mats

start() ->
   spawn(fun init/0) ! {hello,self()},
   receive {ok,Pid} -> Pid
   end.

init() ->
   receive {hello,Daddy} -> ok end,
   try register(name,self()), Daddy ! {ok,self()}
   catch error:badarg -> Daddy ! {ok,whereis(name)},exit(normal)
   end,
   loop().





More information about the erlang-questions mailing list