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

I Gusti Ngurah Oka Prinarjaya okaprinarjaya@REDACTED
Sat Mar 9 14:41:01 CET 2019


Hi Attila Rajmund Nohl,

After i implement your suggestion, i get error when execute any of function
call_the_*_p()
for example:

3> newbie:starter().

<0.112.0>

4> newbie:call_the_second().

=ERROR REPORT==== 9-Mar-2019::20:35:15.069388 ===

Error in process <0.113.0> with exit value:

{badarg,[{erlang,register,[pidsecondp,<0.113.0>],[]},

         {newbie,the_second_p,0,


[{file,"/Users/okaprinarjaya/Oprek/Erlang-Oprek/oprek-lagi/src/newbie.erl"},

                  {line,17}]}]}


{<0.113.0>,"the_second_p()","Halo second p!"}

This is my new modified code https://pastebin.com/iYCxkkuz


Pada tanggal Jum, 8 Mar 2019 pukul 21.03 Attila Rajmund Nohl <
attila.r.nohl@REDACTED> menulis:

> 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.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20190309/43e5a209/attachment.htm>


More information about the erlang-questions mailing list