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

Hakan Mattsson hakan@REDACTED
Wed Feb 7 12:04:45 CET 2007

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>    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. 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) ->
      _ ->
        spawn(my_mod, my_server, []), 

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.

MC> this is also not safe;
MC>    my_service:start(),
MC>    my_service ! hello.

In which regard is it not safe?


More information about the erlang-questions mailing list