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

Mats Cronqvist <>
Wed Feb 7 12:35:34 CET 2007


Hakan Mattsson wrote:
> On Wed, 7 Feb 2007, Mats Cronqvist wrote:
> 
> MC> Hakan Mattsson wrote:
> MC> > On Tue, 6 Feb 2007, Robert Virding wrote:
> MC> > 
> MC> > RV> Torbjorn Tornkvist wrote:
> MC> > RV> > Either let the users of the library start it with
> MC> > RV> > a start function or you could let every function
> MC> > RV> > do it automatically. Example:
> MC> > RV> > 
> MC> > RV> > start() ->
> MC> > RV> >   case whereis(my_service) of
> MC> > RV> >     Pid when pid(Pid) -> Pid
> MC> > RV> >     _ -> spawn(my_mod, my_server, [])
> MC> > RV> >   end.
> MC> > RV> 
> MC> > RV> That start function is not safe, especially on an SMP system. You could 
> MC> > RV> get two rocesses running start simultaneously both not finding the 
> MC> > RV> server and both trying to start it.
> MC> > 
> MC> > The start function is safe. Only one of the processes
> MC> > will succeed in registering the name my_service.
> MC> 
> MC>    it's not safe if start/0 is supposed to return the pid of the server.
> 
> Ok it is not safe in that particular regard if the pid
> really is intended to be used, but as Tobbe did not use
> in his example I assumed that that it was not intended
> to be used. 

   i think it's clear from tobbes code that he intended it to return the correct 
pid. and i think it should.

> If it is important that the correct pid
> is returned you will need to change the example to:
>   start() ->
>     case whereis(my_service) of
>       Pid when pid(Pid) ->
>         Pid
>       _ ->
>         spawn(my_mod, my_server, []), 
>         whereis(my_service)
>     end.

   the second whereis/1 will (likely) run before the register/2 call (presumably 
present) in my_mod:my_server/0, and so will return undefined.

> Then of course you may extend the example to also
> handle the case when the process crashes in its
> startup. But neither that nor the problem that you
> pointed out has nothing to do with the problem that
> Robert mentioned.

   true enough. it's the server instances problem to figure out if there is 
already another instance running.

> MC> this is also not safe;
> MC> 
> MC>    my_service:start(),
> MC>    my_service ! hello.
> 
> In which regard is it not safe?

   the same reason as above; the send/2 ("!") will (likely) run before the 
register/2 (since the spawned process will likely not run immediately), and so 
will exit with badarg.

   mats



More information about the erlang-questions mailing list