[erlang-questions] [Code Review] Is this a good idea? I linking 3 process manually (not using recursive)

Attila Rajmund Nohl attila.r.nohl@REDACTED
Fri Mar 8 15:03:27 CET 2019


I Gusti Ngurah Oka Prinarjaya <okaprinarjaya@REDACTED> ezt írta
(időpont: 2019. márc. 8., P, 12:11):
>
> Hi Folks,
>
> I need your help to review my code. I create and linking 3 process manually without using recursive. And inside p1 and p2 i using IF statement to check to make sure spawning process will only once.
>
> I mean, is part code below is a good idea?
>
> IsPidExists = whereis(xxx),
>   if IsPidExists =:= undefined ->
>     Pid = spawn_link(?MODULE, the_p, []),
>     register(xxx, Pid);
>     true -> true
>   end,

Generally this is not a good idea, there's a race condition between
checking that the process is registered (the whereis/1 call) and
registering the new process. A better idea is to start the process and
let the process itself to register. If register fails, it means that
there's already a process registered, so the just started process can
terminate. So your code could look like something like this:

starter() ->
  spawn(?MODULE, the_first_p, []).

the_first_p() ->
  register(pidfirstp, self()),
  spawn_link(?MODULE, the_second_p, []),
  ...
  the_first_p().

Actually if the register call fails, it throws a badarg and the
process dies automatically, simplifying the code.



More information about the erlang-questions mailing list