[erlang-questions] Programming Erlang Exercise 8.11
Charles Gordon
charles.gordon@REDACTED
Thu Sep 20 07:29:38 CEST 2007
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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20070919/e2668e8a/attachment.htm>
More information about the erlang-questions
mailing list