[erlang-questions] Question regarding problems in Joe's book

jla415 jla415@REDACTED
Sat Jul 28 11:34:03 CEST 2007



Mike Berrow wrote:
> 
> % 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.
> -module(sfun).
> -export([start/2]).
> 
> start(AnAtom, Fun) -> 
>   case whereis(AnAtom) of
>     undefined -> register(AnAtom, spawn(Fun)), succeed;
>     _Else -> fail
>     %_Else -> throw(already_started)
>   end.
> 

The problem with this particular example is that it's possible for another
process to register the name between the time this one checks and does its
registration (and if that happens the spawned process is still left running
unregistered and you have 2 processes running.)

I believe Joe was looking for something more along the lines of:

start(Name, Fun) ->	
    spawn(Fun() ->
		 register(Name, self()),
		 Fun() 
	 end).

Which first starts the new process, tries to register itself then continues
on with the Fun when it succeeds. If it was already registered it will fail
with a badarg thrown and the newly spawned process will die.

It seems like there should be something in otp that handles this sort of
pattern for us but if there is I can't recall off the top of my head... I'm
generally using gen_servers and the like when dealing with registered
processes so this issue doesn't seem to come up much in practice.
-- 
View this message in context: http://www.nabble.com/Question-regarding-problems-in-Joe%27s-book-tf4160373.html#a11841008
Sent from the Erlang Questions mailing list archive at Nabble.com.




More information about the erlang-questions mailing list