[erlang-questions] Programming Erlang Exercise 8.11

igwan igwan@REDACTED
Thu Sep 20 08:50:04 CEST 2007


One solution would be to make the new spawned process call register/2 
before calling Fun, but in this case you would use spawn_link instead of 
spawn to cause the process calling the start function to exit when the 
name is already registered :

start(AnAtom, Fun) ->
    Fun2 = fun() -> register(AnAtom, self()), Fun() end,


Charles Gordon a écrit :
> I'm new to Erlang and working my way through Joe Armstrong's 
> "Programming Erlang". I'm a little stumped by exercise 8.11, and I'm 
> hoping someone can give me a hint or two. Here is the full text of the 
> exercise for those of you without the book:
> "Write a function start(AnAtom, Fun) to register AnAtom as spawn(Fun). 
> Make sure your program works correctly in the case when two parallel 
> processes simultaneously evaluate start/2. In this case, you must 
> guarantee that one of these processes succeeds and the other fails."
> I think I understand the problem to mean that start(AnAtom, Fun) 
> should spawn(Fun) and then register the resulting Pid with AnAtom. 
> Here is my best shot at such a function:
>  start(AnAtom, Fun) ->
>      case whereis(AnAtom) of
>          undefined ->
>              Pid = spawn(Fun),
>              register(AnAtom, Pid);
>          true ->
>              true
>      end.
> The problem didn't specify what the function should return after the 
> first call, so I'm just returning "true" (since that is what 
> "register/2" returns). The trouble I'm having is that I can't see how 
> this avoids a race condition. I don't understand what underlying 
> mechanisms ensure that two parallel processes calling this function 
> don't both evaluate "whereis(AnAtom)", both get "undefined" and both 
> spawn the process (and register it). The problem here is that whereis 
> and register seem to be accessing some sort of shared global state, 
> which is supposed to be impossible. At least, I think they are, since 
> I can't understand how else they would work. What am I missing here?
> Thanks!
> Charles Gordon
> ------------------------------------------------------------------------
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions

More information about the erlang-questions mailing list