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:
<br><br>"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."
<br><br>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:<br><br> start(AnAtom, Fun) -><br> case whereis(AnAtom) of
<br> undefined -><br> Pid = spawn(Fun),<br> register(AnAtom, Pid);<br> true -><br> true<br> end.<br><br>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?
<br><br>Thanks!<br>Charles Gordon<br><br>